Sunday, February 10, 2013

JPQL vs. Criteria


Document  Version 1.0
A simple  "User.java" persistence entity will be used in test. To make the test simple, we will just test "SELECT" behavior of the JPQL and Criteria.

1. The persistence entity "User.java":

The "User.java" class has only 2 fields:

  • id, of type Long
  • name,  of type String

2. Coding Effort: "SELECT" User


"SELECT" using JPQL:

...
Query q = em.createQuery("SELECT u From User u WHERE u.name=:name",
User.class);
q.setParameter("name", "hehe");

List<User> result = q.getResultList();
...
                     


"SELECT" using Criteria API:

...

CriteriaQuery<User> query =cb.createQuery(User.class);
Root<User> aUser = query.from(User.class);
query.where(cb.equal(aUser.<String>get("name"), cb.parameter(String.class, "userName")));

TypedQuery<User> tq = em.createQuery(query);
tq.setParameter("userName", "hehe");

List<User> result = tq.getResultList();
...

Apparently the coding effort using JPQL is less than that when using Criteria.



3. Usability: "SELECT" User

For someone who is familar with SQL, he might feel very comfortable with JPQL syntax, however Criteria is not so straightforward.

For someone who use Criteria, he must also know what is SQL "from", "where".., so he is not going to have big problem with JPQL.


4. Performance   

According to JPA documentation,  "JPQL query is parsed for each call", where Criteria NOT, so criteria should perfoms better.

We will take data retrieve as example, to see if and how much is the performance diference actually.

Test run 1:



Test run 2:


The averave of 2 test runs:


The conclusion:


1 comment: