JPA Named Queries vs Criteria API?

kostja picture kostja · Sep 7, 2011 · Viewed 20.5k times · Source

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

Answer

James picture James · Sep 7, 2011

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.