Criteria queries in Hibernate

Where we have several optional search criteria to deal with, criteria queries prove to be a much better alternative. So basically, it’s close to what we had done for named query. Let’s check out how we can write and execute a criteria query.

We had already done the following in our previous articles –

May be if you missed out any of the above topics, you may revisit the above articles and complete the setup on your systems.

To what we had done with named queries, taking the same example, we write a new controller method searchByEmailIdWithCriteria and map it to a URL pattern, say “/searchByEmailCriteria“.

When we go the actual DAO layer implementation of the searchByEmailIdWithCriteria method, it looks something like –

Now change the search form action to “searchByEmailCriteria“, and run the application on the server.

The output is no different for what we had implemented using named query.

You might find Expression being used in place of Restrictions in some of the examples on the internet. Basically, we prefer using Restrictions only, as Expression has been deprecated.

You can read more on Restrictions functions here.

Named HQL Query vs Criteria Query vs Non-named HQL Query

Criteria, in theory should have less overhead than a non-named HQL query. This is because a Criteria doesn’t need to parse anything. HQL queries are parsed with an ANTLR-based parser and then the resulting AST output is turned into SQL. However, with HQL/JPAQL we can also write named queries, where the SQL is generated when the SessionFactory starts up. In theory, named queries have even less overhead than Criteria.

So, in terms of SQL-generation overhead we have –

  1. Named HQL/JPAQL Query – SQL generation happens only once.
  2. Criteria Query – No need to parse before generating.
  3. Non-named HQL/JPAQL Query – Parse, then generate.

We can also write a Criteria Query with an object property as restriction. Learn more

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.