hibernate

Hibernate Criteria Example

Photo of Nikos MaravitsasNikos MaravitsasJuly 20th, 2013Last Updated: February 21st, 2019
0 164 3 minutes read

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 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 persistedStudentInformation instances that satisfy a number of conditions about theirenlisted 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 ");       if(sDate!=null){    if(isFirstSearchCriterion){    query.append(" where enlisted >= '" + date.format(sDate) + "'");    }else{    query.append(" and enlisted >= '" + date.format(sDate) + "'");    }    isFirstSearchCriterion = false;       }       if(eDate!=null){    if(isFirstSearchCriterion){    query.append(" where enlisted <= '" + date.format(eDate) + "'");    }else{    query.append(" and enlisted <= '" + date.format(eDate) + "'");    }    isFirstSearchCriterion = false;       }       if(address!=null){    if(isFirstSearchCriterion){    query.append(" where address = '" + address+"'");    }else{    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 thewhere clause, check if it’snull 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));}criteria.addOrder(Order.asc("date"));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

Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright 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!

Thank you!

We will contact you soon.

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));

Restrictions.like

This is offers the same functionality as SQLLIKE clauses:

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

Restrictions.between

Retrive instances that theirenlisted 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);criteria.setMaxResults(8);criteria.setFirstResult(100);

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

Conclusion

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 aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
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 ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Nikos MaravitsasNikos MaravitsasJuly 20th, 2013Last Updated: February 21st, 2019
0 164 3 minutes read
Photo of 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.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.