Hi Guys! I am back with a new blog post titled “Filtering Records using Hibernate Criteria”. I often use Hibernate Criteria in my project whenever a new entity is added and I need to implement certain filters on it.

The Hibernate Session provides createCriteria() method that returns a Criteria object which can be used to fetch list of persistent objects by interacting with the database. Criteria can be used to impose various conditions while querying something from the database like we do in SQL using where clause.

We can use Criteria’s add() method to add restriction/conditions for a criteria query.

To create a criteria we first need to obtain hibernate session and then invoke the createCriteria() method.

For example to fetch all the records with income greater than 500000 we can use the following:

Criteria cr = getSession().createCriteria(Person.class);
cr.add(Restrictions.gt("income", 500000));

Other examples:-

// Fetch orders with status 5
Criteria criteria = session.createCriteria(PurchaseOrder.class);
criteria.add(Restrictions.eq("orderStatus", 5));

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

// Fetch records having name starting with vi
cr.add(Restrictions.like("name", "vi%"));

// Case in-sensitive form of Like.(Using ilike)
cr.add(Restrictions.ilike("name", "vi%"));

// To get records having age between 20 and 50
cr.add(Restrictions.between("age", 20, 50));

// To check if  a property is null
cr.add(Restrictions.isNull("age"));

// To check if a property is not null
cr.add(Restrictions.isNotNull("age"));

We can also create AND/OR conditions using LogicalExpression like this:-

Criteria orCriteria = session.createCriteria(Employee.class);
Criterion salary = Restrictions.gt("salary", 20000);
Criterion name = Restrictions.ilike("name","ra%");

// Fetch records with the OR condition
LogicalExpression expression = Restrictions.or(salary, name);
orCriteria.add( expression );

The above “orCriteria” will fetch those records where the salary is greater than 20000 OR “name” starts with “ra”

After specifying the Criteria we can also specify the order in which we want the records like this:-

orCriteria.addOrder(Order.desc("salary"))

To execute the query we use list() method like this:-

List list = orCriteria.list();

The above code will fetch the list of objects satisfying the conditions/restrictions specified.

That was all about Hibernate Criteria. I will come up with more posts on Hibernate and also share the issues Which I faced in my project while using criteria.

Thanks 🙂