Hibernate Criteria Query API

The Criteria interface allows to create and execute object-oriented queries. It is powerful alternative to the HQL but has own limitations. Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective.

  • The Criteria interface is in the org.hibernate package. 
  • It is a very convenient approach for applying a variable number of conditions to a search. 
  • Since Criteria is an interface, it can’t be instantiated. Instead, the Session class has a factory method called createCriteria, which takes a reference of type Class.                                                                 Criteria crit = session.createCriteria(User.class); 
  • The Criteria Query API provides an object-oriented way to build complex queries. 
  • The list method and the uniqueResult method return all instances of a class and a single instance, respectively. 
  • Constraints on a query are applied using static factory methods from the Restrictions class. 
  • Projections are used to compute scalar quantities from results, like count, max, or min. 
  • Projections can be applied to properties, associations, and 
  • more. 
  • The Query by Example capability lets Hibernate construct a query based on a sample object.  
Sample Criteria Example:
SessionFactory sessionFactory = new Configuration().configure().
Session session = sessionFactory().getCurrentSession();
Criteria crit = session.createCriteria(Employee.class); 
List<Employee> emps = crit.list();