Skip to content

Criteria API in Hibernate and Usage in CARE Project

August 10, 2009

Criteria API in Hibernate

1.Criteria is a simplified API for retrieving entities by composing Criterion objects. This is the easy approach for searching the values from the various number of conditions.

2. The interface org.hibernate.Criteria is used to create the criterion for the search. The org.hibernate.Criteria interface represents a query against a persistent class.

In order to know more about the details of the Criteria API, it is better to classify it in to the following sub topics,

1.What is Criteria query?

2. How to use Criteria query API?


4. Restrictions

5. Ordering

6. Aggregate functions

7. Usage of Criteria in CARE Project

1. What is Criteria Query?

In order to retrieve values from the data base using the opject relational mapping the Criteria API provides the

easy way of forming the dynamic query and executing it.

Three ways of retrieving data in Hibernate

The data from the database can be fetched by using any one of the three ways given below,

￯﾿ᄁ￯ᄒラ? Criteria query API

￯﾿ᄁ￯ᄒタ￯ᄒモ The easiest way to retrieve data

￯﾿ᄁ￯ᄒタ￯ᄒモ Pure Java language based

￯﾿ᄁ￯ᄒラ? Hibernate Query Language (HQL)

￯﾿ᄁ￯ᄒラ? Native SQL query

Criteria Query API

￯﾿ᄁ￯ᄒラ? Provides a set of Java objects for constructing Queries

￯﾿ᄁ￯ᄒラ? Lets you build nested, structured query expressions in Java programming language

￯﾿ᄁ￯ᄒタ￯ᄒモ Compile time syntax checking possible

￯﾿ᄁ￯ᄒタ￯ᄒモ Polymorphic behavior

￯﾿ᄁ￯ᄒラ? Supports Query By Example (QBE)

￯﾿ᄁ￯ᄒタ￯ᄒモ Performing a query by providing an example object that contain properties that need to be retrieved

￯﾿ᄁ￯ᄒラ? Supports aggregation methods (from Hibernate 3)

￯﾿ᄁ￯ᄒタ￯ᄒモ Count

2. How to use Criteria Query API

The following steps has to be done to retrieve values,

￯﾿ᄁ￯ᄒラ? Create org.hibernate.Criteria object via createCriteria() factory method of the Session

￯﾿ᄁ￯ᄒタ￯ᄒモ Pass persistent object’s class or its entity name to the createCriteria() method

￯﾿ᄁ￯ᄒラ? Call list() method of the Criteria object

// Get all instances of Person class and its subclasses

Criteria crit = sess.createCriteria(Person.class);

List results = crit.list();

3. Pagination

By using Criteria query we can make the Pagination, like retrieve the first value from the table or

retrieve first 50 Row from the table

Pagination through the Result Set

￯﾿ᄁ￯ᄒラ? Hibernate handles the pagination

￯﾿ᄁ￯ᄒタ￯ᄒモ Retrieving fixed number of objects

￯﾿ᄁ￯ᄒラ? Two methods of Criteria class

￯﾿ᄁ￯ᄒタ￯ᄒモ setFirstResult() – set the first row in the result

￯﾿ᄁ￯ᄒタ￯ᄒモ setMaxResults() – number of rows to retrieve

Criteria crit = sess.createCriteria(Person.class);



List results = crit.list();

4. Restrictions class

This class provides teh ability to add where conditions like the equal, not equal, like ,etc., in the query.

￯﾿ᄁ￯ᄒラ? Used to selectively retrieve objects

￯﾿ᄁ￯ᄒタ￯ᄒモ Person objects whose age is over 20

￯﾿ᄁ￯ᄒラ? Add restrictions to the Criteria query object with add() method

￯﾿ᄁ￯ᄒタ￯ᄒモ The add() method of the Criteria object takes an org.hibernate.criterion.Criterion object that

represents an individual restriction

￯﾿ᄁ￯ᄒラ? You can have more than one restriction for a Criteria query

Methods of Restrictions class

The following are the methods that are available in the Restrictions class for adding the

where condition in the Criteria Query.

￯﾿ᄁ￯ᄒラ? Restrictions.eq(￯﾿ᄁ￯ᄒタ￯ᄒワname￯﾿ᄁ￯ᄒタ?, ￯﾿ᄁ￯ᄒタ?Shin￯﾿ᄁ￯ᄒタ?)

￯﾿ᄁ￯ᄒラ?￯﾿ᄁ￯ᄒタ￯ᄒワname￯﾿ᄁ￯ᄒタ?, ￯﾿ᄁ￯ᄒタ?NoName￯﾿ᄁ￯ᄒタ?)

￯﾿ᄁ￯ᄒラ?￯﾿ᄁ￯ᄒタ￯ᄒワname￯﾿ᄁ￯ᄒタ?, ￯﾿ᄁ￯ᄒタ￯ᄒワSa%￯﾿ᄁ￯ᄒタ?)

￯﾿ᄁ￯ᄒラ? Restrictions.ilike(￯﾿ᄁ￯ᄒタ￯ᄒワname￯﾿ᄁ￯ᄒタ?, ￯﾿ᄁ￯ᄒタ￯ᄒワsa%￯﾿ᄁ￯ᄒタ?)

￯﾿ᄁ￯ᄒラ? Restrictions.isNull(￯﾿ᄁ￯ᄒタ￯ᄒワname￯﾿ᄁ￯ᄒタ?);

￯﾿ᄁ￯ᄒラ?￯﾿ᄁ￯ᄒタ￯ᄒワprice￯﾿ᄁ￯ᄒタ?,new Double(30.0))

￯﾿ᄁ￯ᄒラ? Restrictions.between(￯﾿ᄁ￯ᄒタ￯ᄒワage￯﾿ᄁ￯ᄒタ?, new Integer(2), new Integer(10))

￯﾿ᄁ￯ᄒラ? Restrictions.or(criterion1, criterion2)

￯﾿ᄁ￯ᄒラ? Restrictions.disjunction()

Add a restriction

The following is the where condition with the like method example.


// Retrieve person objects whose name has a pattern

Criteria crit = sess.createCriteria(Person.class);

Criterion nameRestriction =“name”,“Shin%”);

crit.add( nameRestriction );

List results = crit.list();

5. Ordering the Result Set

Ordering the results

By using the Criteria Query we can arrange the result set either Ascending or Descending order,

as we do in the SQL query

￯﾿ᄁ￯ᄒラ? You may order the results using org.hibernate.criterion.Order

List cats = sess.createCriteria(Cat.class)

.add(“name”, “F%”)

.addOrder( Order.asc(“name”) )

.addOrder( Order.desc(“age”) )



6. Projections and Aggregate Functions

Aggregate functions available through Projections factory class

In order to make arithmatic calculations we have so mant methods like avg(), Count(), max(), etc., in to make use of it.

￯﾿ᄁ￯ᄒラ? avg(String propertyName)

￯﾿ᄁ￯ᄒタ￯ᄒモ average of a property’s value

￯﾿ᄁ￯ᄒラ? count(String propertyName)

￯﾿ᄁ￯ᄒタ￯ᄒモ number of times a property has a value

￯﾿ᄁ￯ᄒラ? countDistinct(String propertyName)

￯﾿ᄁ￯ᄒタ￯ᄒモ number of unique values the property contains

￯﾿ᄁ￯ᄒラ? max(String propertyName)

￯﾿ᄁ￯ᄒラ? min(String propertyName)

￯﾿ᄁ￯ᄒラ? sum(String propertyName)

￯﾿ᄁ￯ᄒタ￯ᄒモ sum of the property values

Thus the Criteria query provides all most all the facilities to retrieve values from the

data base in the form of objects, with all most all the facilities that are available in the SQL queries.

7. Real Time Example in CARE Project

In the CARE project, during search, when we serach by using the key, we go for the

Criteria API to get the values from the Database.

public List findObjectsByKey(final Class objectType, final EntityVOKey key)

throws DAOException {

Criteria criteria = createPkCriteria(key, objectType);

return findByCriteria(criteria);


In this method the key and the Mapping class for the table from where the data has to be fetched will be passed.

Criteria createPkCriteria(final EntityVOKey pk, final Class clazz) throws DAOException {

final int getLength = 3;

Session session = openSession();

Criteria criteria = session.createCriteria(clazz);

Method[] methods = pk.getClass().getDeclaredMethods();

try {

for (int i = 0; i < methods.length; i++) {

String name = methods[i].getName();

if (name.startsWith(“get”)) {

name = name.substring(getLength);

Object value = methods[i].invoke(pk, null);

Criterion criterion = Expression.eq(name, value);




} catch (Exception e) {



return criteria;


In this method the actual values will be fetched and the values are returned to the methods

which ever calls the finObjectsByKey () method with the key and the Pojo class for the

corresponding table from where the values has to be fetched.

final List findByCriteria(final Criteria criteria) throws DAOException {

List ret = null;

Session session = null;

try {

session = openSession();

ret = criteria.list();

} catch (final Exception ex) {


} finally {



return ret;


No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: