I have taken a look at JPA 2.0 Criteria API, but I found it to be too cumbersome unlike Hibernate Criteria. Is there any good reason to use JPA 2.0 Criteria API rather than using JPA-QL? Thanks for your advise.
The Criteria API is used to define queries for entities and their persistent state by creating query-defining objects. Criteria queries are written using Java programming language APIs, are typesafe, and are portable. Such queries work regardless of the underlying data store.
In Hibernate, the Criteria API helps us build criteria query objects dynamically. Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements.
Like the Hibernate Criteria API, the JPA 2.0 Criteria API is especially nice to build queries dynamically, to handle cases where the query structure varies depending upon runtime conditions.
But there is more. While being more verbose than Hibernate's Criteria API, the JPA Criteria API allows to build typesafe queries (if you use the Metamodel API). Below an example:
EntityManager em = ... QueryBuilder qb = em.getQueryBuilder(); CriteriaQuery<Person> c = qb.createQuery(Person.class); Root<Person> p = c.from(Person.class); Predicate condition = qb.gt(p.get(Person_.age), 20); c.where(condition); TypedQuery<Person> q = em.createQuery(c); List<Person> result = q.getResultList();
In the above snippet, the following would raise a compilation error for example:
Predicate condition = qb.gt(p.get(Person_.age, "xyz"));
In case you wonder, Person_
is the static, instantiated, canonical metamodel class corresponding to the original Person
entity class (generated by an annotation processor). It provides a strongly typed alternative to a runtime reflection based approach:
Field field = Person.class.getField("age");
Pros:
Cons:
I feel in general more comfortable with JPQL but the type safety of the Criteria API is a major difference with JPQL (and also the Hibernate Criteria API).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With