Hibernate Criteria

HCQL (Hibernate Criteria Query Language)

The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the specific criteria. The Criteria interface provides methods to apply criteria such as retrieving all the records of table whose salary is greater than 50000 etc.

Advantage of HCQL

The HCQL provides methods to add criteria, so it is easy for the java programmer to add criteria. The java programmer is able to add many criteria on a query.

Criteria Interface

The Criteria interface provides many methods to specify criteria. The object of Criteria can be obtained by calling the createCriteria() method of Session interface.

HQL Example:

Imagine you want to write a method which searches for persisted Student Information 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 “);                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 operation 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 condition is going to be first appended in the where clause, check if it’s null and so on. Imagine what happens when dealing with substantially 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:

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

Criteria ordering query:

Ascending order:asc()

Descending order:desc()

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

Criteria restrictions query:

This is one of the most useful tools that Criteria framework has to offer. Let’s say you want to retrieve StudentInformation with id equal (eq), greater (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:

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

Restrictions.between:

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

Restrictions.isNull, isNotNull:

Criteria criteria = session.createCriteria(StudentInformation.class).add(Restrictions.isNull(“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;