Home » Enterprise Java » hibernate » Hibernate Criteria Example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Hibernate Criteria Example

Hibernate Criteria is a very good interface offered by Hibernate that helps you write queries with comples search criteteria an keep your code readable and elegant.

So these are the tools we are going to use on a Windows 7 platform:

  • JDK 1.7
  • Maven 3.0.5
  • Hibernate 3.6.3.Final
  • MySQL JDBC driver 5.1.9
  • Eclipse 4.2 Juno

Want to be a Hibernate Master ?

Subscribe to our newsletter and download the Hibernate Ultimate Guide right now!

In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!


The basis of this tutorials is going to be this Eclipse project: Hibernate1to1XMLExample,zip. And it’s based in Hibernate One-to-One Relationship Example (XML Mapping and Annotation). All the code snippets displayed here reffer to App.java file of the aforementioned project. It’s also a good idea to take a look at Hibernate Query Language Example.

HQL example

Imagine you want to write a method which searches for persisted StudentInformation instances that satisfy a number of conditions about their enlisted date, or any of their properties for that matter. You could write something like that in HQL.

 public static List getStudentInformation(Date sDate,Date eDate,String address,Session session){

    		   SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
    		   boolean isFirstSearchCriterion = true; 

    		   StringBuilder query = new StringBuilder("from StudentInformation ");

    				query.append(" where enlisted >= '" + date.format(sDate) + "'");
    				query.append(" and enlisted >= '" + date.format(sDate) + "'");
    			isFirstSearchCriterion = false;

    				query.append(" where enlisted <= '" + date.format(eDate) + "'");
    				query.append(" and enlisted <= '" + date.format(eDate) + "'");
    			isFirstSearchCriterion = false;

    				query.append(" where address = '" + address+"'");
    				query.append(" and address = '" + address+"'");
    			isFirstSearchCriterion = false;

    		   query.append(" order by date");
    		   Query result = session.createQuery(query.toString());

    		   return result.list();

The main problem here is that you have to do a complex string appending opperation which is a bit tedious, let alone error prone. As you know, blind string appending of unsunititezed input is vulnerable to SQL Injection attacks. Here, we have to know which condtition is going to be first appended in the where clause, check if it’s null and so on. Imagine what happens when dealing with substantiallu bigger classes and queries that need to satisfy more complex conditions.

Using Criteria you can write the above code like so:

public static List getStudentInformation(Date sDate, Date eDate,
			String address, Session session) {
		Criteria criteria = session.createCriteria(StudentInformation.class);
		if (sDate != null) {
			criteria.add(Expression.ge("date", sDate));
		if (eDate != null) {
			criteria.add(Expression.le("date", eDate));
		if (address != null) {
			criteria.add(Expression.eq("address", address));

		return criteria.list();

So, you can simply append search criteria to the query using simple expressions.

Criteria basic query

This how you can create a simple Criteria object:

Criteria criteria = session.createCriteria(StudentInformation.class);

Criteria ordering query

If you want to sort by date in ascending order:

Criteria criteria = session.createCriteria(StudentInformation.class).addOrder( Order.asc("date") );

or with descending order:

Criteria criteria = session.createCriteria(StudentInformation.class).addOrder( Order.desc("date") );

Criteria restrictions query

This is one of the most usefull tools that Criteria framework has to offer. Let’s say you want to retrieve StudentInformation with id equal (eq), geater (gt), greater equal (ge), less equal (le). less that (lt) a certain number, let’say 20:

Restrictions.lt, le, gt, ge

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.eq("id", 20));

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.gt("id", 20));

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.ge("id", 20));

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.lt("id", 20));

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.le("id", 20));


This is offers the same functionality as SQL LIKE clauses:

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.like("address", "street 1%"));


Retrive instances that their enlisted date is in certain period:

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.between("date",sdate,edate));

Restrictions.isNull, isNotNull

This is very usefull when you want to check if a certain property of the persisted class is null:

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.isNull("date"));

or not null:

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.isNotNull("date"));

Paging the result

If you have a vastly populated database and your end up retrieving a big number of results from your queris, Criteria offers some methods that make pagination easy. For example you can choose the range of results that you want to retrieve like so:

Criteria criteria = session.createCriteria(StudentInformation.class);

Here we chose to retrieve results 8 to 100 from the result list.


In all the above examples you can use the session object created by Criteria in the same way we saw for the perivous Hibernate tutorials. So as you can see it’s a very handy tool when you want to keep your code clean and elegant especially when you have to make queries that need to satisfy lots of conditions. One major disadvantage when using Criteria is ther is no control over the way that queries are tanslated and executed, and that might not be acceptable for high performance systems.

This was an example on Hibernate Criteria.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns