Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

java - What are some of the real world example where JPA2 Criteria API is more preferable?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • Type safety, compile time verification!
    • Prohibits the construction of queries that are syntactically incorrect.
    • Can raise a compilation error after a refactoring.
    • Provides out of the box support for auto-completion
  • Better suited for dynamic queries.

Cons:

  • More verbose.
  • Less readable.

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).

See also

Related answers


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...