Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Named Queries vs Criteria API?

Is there a heuristic/best practice/ruleset for a decision between the Criteria API and NamedQuery?

My thoughts so far :
Named queries are generally more readable. Criteria queries are more flexible.
Both are precompiled. I tend to rely on using named queries as long as possible, then changing to criteria.

But maybe the urge to "flexify" the query by using the criteria API is a hint to suboptimal design (i.e. separation of concerns)?

Thank you

like image 340
kostja Avatar asked Sep 07 '11 12:09

kostja


People also ask

What is difference between named queries and criteria queries?

Named queries are more optimal (they are parsed/prepared once). Criteria queries are dynamic, (they are not precompiled, although some JPA providers such as EclipseLink maintain a criteria prepare cache).

Is Criteria API deprecated?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.

What is JPA Criteria API?

The Criteria API is a predefined API used to define queries for entities. It is the alternative way of defining a JPQL query. These queries are type-safe, and portable and easy to modify by changing the syntax.

Which is faster JPQL or native query?

In some cases it can happen Hibernate/JPA does not generate the most efficient statements, so then native SQL can be faster - but with native SQL your application loses the portability from one database to another, so normally is better to tune the Hibernate/JPA Query mapping and the HQL statement to generate more ...


1 Answers

Named queries are more optimal (they are parsed/prepared once). Criteria queries are dynamic, (they are not precompiled, although some JPA providers such as EclipseLink maintain a criteria prepare cache).

I would use criteria only for dynamic queries.

like image 88
James Avatar answered Sep 18 '22 22:09

James