Hibernate Criteria examples
Hibernate Criteria API is a more object oriented and elegant alternative to Hibernate Query Language (HQL). It’s always a good solution to an application which has many optional search criteria.
Example in HQL and Criteria
Here’s a case study to retrieve a list of StockDailyRecord, with optional search criteria – start date, end date and volume, order by date.
1. HQL example
In HQL, you need to compare whether this is the first criteria to append the ‘where’ syntax, and format the date to a suitable format. It’s work, but the long codes are ugly, cumbersome and error-prone string concatenation may cause security concern like SQL injection.
public static List getStockDailtRecord(Date startDate,Date endDate, Long volume,Session session){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); boolean isFirst = true; StringBuilder query = new StringBuilder("from StockDailyRecord "); if(startDate!=null){ if(isFirst){ query.append(" where date >= '" + sdf.format(startDate) + "'"); }else{ query.append(" and date >= '" + sdf.format(startDate) + "'"); } isFirst = false; } if(endDate!=null){ if(isFirst){ query.append(" where date <= '" + sdf.format(endDate) + "'"); }else{ query.append(" and date <= '" + sdf.format(endDate) + "'"); } isFirst = false; } if(volume!=null){ if(isFirst){ query.append(" where volume >= " + volume); }else{ query.append(" and volume >= " + volume); } isFirst = false; } query.append(" order by date"); Query result = session.createQuery(query.toString()); return result.list(); }
2. Criteria example
In Criteria, you do not need to compare whether this is the first criteria to append the ‘where’ syntax, nor format the date. The line of code is reduce and everything is handled in a more elegant and object oriented way.
public static List getStockDailyRecordCriteria(Date startDate,Date endDate, Long volume,Session session){ Criteria criteria = session.createCriteria(StockDailyRecord.class); if(startDate!=null){ criteria.add(Expression.ge("date",startDate)); } if(endDate!=null){ criteria.add(Expression.le("date",endDate)); } if(volume!=null){ criteria.add(Expression.ge("volume",volume)); } criteria.addOrder(Order.asc("date")); return criteria.list(); }
Criteria API
Let go through some popular Criteria API functions.
1. Criteria basic query
Create a criteria object and retrieve all the ‘StockDailyRecord’ records from database.
Criteria criteria = session.createCriteria(StockDailyRecord.class);
2. Criteria ordering query
The result is sort by ‘date’ in ascending order.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .addOrder( Order.asc("date") );
The result is sort by ‘date’ in descending order.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .addOrder( Order.desc("date") );
3. Criteria restrictions query
The Restrictions class provide many methods to do the comparison operation.
Restrictions.eq
Make sure the valume is equal to 10000.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.eq("volume", 10000));
Restrictions.lt, le, gt, ge
Make sure the volume is less than 10000.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.lt("volume", 10000));
Make sure the volume is less than or equal to 10000.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.le("volume", 10000));
Make sure the volume is great than 10000.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.gt("volume", 10000));
Make sure the volume is great than or equal to 10000.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.ge("volume", 10000));
Restrictions.like
Make sure the stock name is start with ‘MKYONG’ and follow by any characters.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.like("stockName", "MKYONG%"));
Restrictions.between
Make sure the date is between start date and end date.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.between("date", startDate, endDate));
Restrictions.isNull, isNotNull
Make sure the volume is null.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.isNull("volume"));
Make sure the volume is not null.
Criteria criteria = session.createCriteria(StockDailyRecord.class) .add(Restrictions.isNotNull("volume"));
Many other Restrictions functions can find here.
https://www.hibernate.org/hib_docs/v3/api/org/hibernate/criterion/Restrictions.html
3. Criteria paging the result
Criteria provide few functions to make pagination extremely easy. Starting from the 20th record, and retrieve the next 10 records from database.
Criteria criteria = session.createCriteria(StockDailyRecord.class); criteria.setMaxResults(10); criteria.setFirstResult(20);
Why not Criteria !?
The Criteria API do bring some disadvantages.
1. Performance issue
You have no way to control the SQL query generated by Hibernate, if the generated query is slow, you are very hard to tune the query, and your database administrator may not like it.
1. Maintainece issue
All the SQL queries are scattered through the Java code, when a query went wrong, you may spend time to find the problem query in your application. On the others hand, named queries stored in the Hibernate mapping files are much more easier to maintain.
Conclusion
Nothing is perfect, do consider your project needs and use it wisely.








for example Customer is a class which has reference to Country Class and Country Class has a property CountryName .Now if i want to search customer based on country name how to do? is it right to provide
assuming country is the reference name for Country class.
Thanks for your tips
if i am using hibernate with spring .. where should i set values for hibernate criteria in the action class or in the dao class?
hi yonk. how can i replace this code to criteria or which is the better way to do a select count using hibernate. thanks a lot.
this is my code..
i am doing this query but take huge time to finish.
thanks a lot.
Very good article. Thanks for such nice tutorial.
Please keep it up Yong.
–Sikinder
Thank you for telling it like it is. There is a point at which we have to consider what is right for the project and not right by the tool. If we insist on using EVERYTHING a tool provides just because we HAVE to use the TOOL – a lot of “architects” are guilty of this – we end up with an inefficient solution.
This is not just problem with Hibernate. This is problem with any ORM tool which we rely on to generate underlying SQL. As is explained in the first couple of chapters of the Hibernate book, just because you don’t want to bother to understand RDBMS or SQL does not mean you can use Hibernate. Hibernate is not a “get out of jail free card” for incompetence.
For any complex query, IMHO Hibernate should NOT be used. It is just not a question of code scattered all over the place. Even if one uses named query, the SQL generated by Hibernate will be sub-optimal when there are multiple search criteria and pagination to consider. One needs to look at the underlying SQL extensions of the database, i.e. T-SQL or PL-SQL or whatever and learn to write SQL queries.
Good ones.
thanks for all the tutorials.
really thx m8…..better than jboss reference!
Cheers
Yeah, you are right. I thought about this, but decided that its still convenient. Because you don’t have to dublicate all the sql strings, that like you said “ugly, cumbersome and error-prone”. It is just another way :)
PS: Thank you for this site which is great, I learned a lot of new things while reading it.
Hello Yong. I’m new in Hibernate, but that code in the first example could be writting in more convenient way, for example:
…
StringBuilder query = new StringBuilder(“from StockDailyRecord”);
if (startDate != null)
query.append(” %s date >= ‘” + sdf.format(startDate) + “‘”);
if (endDate != null)
query.append(” %s date = ” + volume);
query.append(” order by date”);
Query result = session.createQuery(
String.format(query.toString(), “where”, “and”, “and”));
…
How do you think?
yo great! your code is more convenient. Just little concern, if you have a query which accept 10+ conditions, the string format may cause a maintainability issue, cause you need count the “and” string one by one… After all, this will always happened in legacy system.
Hello mkyong,
I would like to build up a criteria with following conditions
- some variables must be checked whether it is null or not.
- query must be in criteria
the outcome must be look like this:
(fieldname1 == var1)
and (if var2 != null (fieldname2 == var2)
and if var3 != null (fieldname3 == var3)
and if var4 != null (fieldname4 == var4) )
or (fieldname5 == null)
I don’t know the way how can I add the middle part with checking null.
Thanks ahead!
Chaba
What about:
StringBuilder query = new StringBuilder(“from StockDailyRecord where 1 = 1″);
This eliminates the need to check the initial condition
[...] Hibernate Criteria examples Criteria examples – basic query, ordering query, restrictions query and paging the result. [...]