Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. 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

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 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("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:, le, gt, ge

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

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

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

Criteria criteria = session.createCriteria(StudentInformation.class).add("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("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.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books