Hibernate Criteria Queries

Criteria Queries-API is one of the api which can be used to manipulate objects.

Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query.

Creating a Criteria instance:

Criteria crit = sess.createCriteria(Employee.class);
List cats = crit.list();

Applying Restrictions:

class org.hibernate.criterion.Restrictions defines factory methods for obtaining certain built-in Criterion types.

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

// Fetch records having salary less than 50000
cr.add(Restrictions.lt("salary", 50000));

// Fetch records having salary more than 50000
cr.add(Restrictions.gt("salary", 50000));

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

// Case sensitive 
cr.add(Restrictions.ilike("name", "Ank%"));

// Fetch records having salary in between 40000 and 50000
cr.add(Restrictions.between("salary", 40000, 50000));

// Fetch records having salary as 50000

// Check if the given property is null

// Check if the given property is not null

// Check if the given property is empty

// Check if the given property is not empty

AND or OR conditions using LogicalExpression restrictions:

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

Criterion salary = Restrictions.gt("salary", 50000);
Criterion name = Restrictions.ilike("name","Ank%");

// Fetch records matching with OR condistions
LogicalExpression orExp = Restrictions.or(salary, name);
cr.add( orExp );

// Fetch records matching with AND condistions
LogicalExpression andExp = Restrictions.and(salary, name);
cr.add( andExp );

List results = cr.list();

Ordering result:

// Fetch
List emps = sess.createCriteria(Employee.class)
    .add( Restrictions.like("name", "Ank%")
    .addOrder( Order.asc("name") )


We can apply restriction on property of embedded object:

Suppose Employee class is embedding Name class(fname,lname) object:

List Employee = session.createCriteria(Employee.class)
.add(Restrictions.eq("name.lastName", "lakha"))

Pagination using Criteria:

Criteria cr = session.createCriteria(Employee.class);
cr.setFirstResult(10);  //represents the first row(10th in DB) in your result set
cr.setMaxResults(50); // fetch 50 result only
List results = cr.list();

Projections & Aggregations:

class org.hibernate.criterion.Projections is a factory for Projection instances.

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

// Fetch total row count.

// Fetch average of a salary.

// Fetch distinct count of a salary.

// Fetch maximum of a salary.

// Fetch minimum of a salary.

// Fetch sum of a salary.