Document Version 1.0
Copyright © 2012-2013 beijing.beijing.012@gmail.com
JPA 2.0 introduced Criteria API for persistence entity manipulation. For those who has been working with JPQL, the question he might ask himself is: what does JPA Criteria has that JPQL NOT?
In the following I will try to compare JPQL and Criteria in the following 3 aspects:
- Coding efforts
- Usability
- Performance
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();
...
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();
...
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:
Thanks, this was helpful
ReplyDelete