Hibernate -- Criteria vs named query

Roam picture Roam · Apr 12, 2014 · Viewed 10.3k times · Source

I'm trying to compare Hibernate Criteria to named queries for performance. i'm aware it all depends on the actual query itself and the last word is on how they profile in runtime. still, trying to sort out what goes into each.

i tried to organize the Q in two parts & looking for verification/correction on both:

PART-1 -- how Hibernate Criteria and named queries work basically:

Criteria works on parameters. In runtime, the query doesn`t need parsing-- has several search and "present-in-form" params like order the results, return them as scrollable etc. Haven't read/verified this, but Criteria works by indexes on fields (based on the parameters set on them) to make it all faster.

So, the advantage of Criteria compared to plain HQL is its speed during execution.

Named queries have the same advantage over HQL-- the query is parsed once at start-up. Then executed from wherever necessary in the application.

PART-2 -- comparing the two:

So in this picture,

how do Criteria and named-queries compare to one another?

Criteria works well for complicated queries across multiple tables and multiple params-- has the means to optimize and thus make the query fast(?)

named-queries have the advantage of "define-once-use-everywhere" and are quite alright for "light" queries-- less complicated searches with small amount of params typically on a single table. even better on frequent queries.

Note: seen the very useful Hibernate Criteria vs HQL: which is faster? among some other discussions.

TIA.

Answer

JB Nizet picture JB Nizet · Apr 12, 2014

You don't choose one over the other based on performance. In the end, it becomes a SQL query anyway, and what matters is the performance of the SQL query.

Executing a SQL query is orders of magnitudes slower than parsing a HQL query and transforming it to SQL. So even if you don't use a named query, the performance won't be significantly worse.

You choose criteria over HQL based on capabilities and readability.

If you want something readable, use a HQL query.

If you want to compose a query dynamically, based on various, optional, search criteria, then the Criteria API allows that, and is more convenient than dynamically composing an HQL query.