Criteria Examples in Hibernate

Criteria in hibernate helps to manipulate objects and data available in database. It allows you to filter out data,apply restrictions, sorting and pagination.

Basic example:

Criteria cr = session.createCriteria(Employee.class);
List employees = cr.list();

Restrictions within Criteria

add() method used to add restrictions within the criteria query.

Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 20000));
List employees = cr.list();

Some more examples:

Criteria cr = session.createCriteria(Employee.class);

// Salary more than 20000
cr.add(Restrictions.gt("salary", 20000));

// Salary less than 20000
cr.add(Restrictions.lt("salary", 20000));

// Having First Name starts with Akash
cr.add(Restrictions.like("firstName", "Akash%"));

// Having salary in between 10000 and 20000
cr.add(Restrictions.between("salary", 10000, 20000));

// To check if the given property is null
cr.add(Restrictions.isNull("salary"));

// To check if the given property is not null
cr.add(Restrictions.isNotNull("salary"));

 

Pagination Using Criteria

Hibernate provides 2 methods for pagination.

1. public Criteria setFirstResult(int firstResult): It takes an integer that represents the first row in your result set, starting with row 0.

2. public Criteria setMaxResults(int maximumResults): It retrieves a fixed number maxResults of objects.

In below example we are fetching the 5 records at a time:

Criteria cr = session.createCriteria(Employee.class);
cr.setFirstResult(1);
cr.setMaxResults(5);
List employees = cr.list();

 

 

 

Leave a Reply

%d bloggers like this: