Hibernate Criteria - example code

The Hibernate Criteria API is a powerful library, which is well adapted for implementing multi-criteria search functionalities where queries must be built on the fly. For example it can be used to return data in a web search form resulting in cleaner, clearer, more reliable, and more maintainable code.

Here are some examples of the Criteria Api.



Basic Criteria (retrieve all data)

Criteria criteria = session.createCriteria(Track.class);

List<Track> tracks = criteria.list();

for (Track track : tracks) {
 System.out.println("Title     = " + track.getTitle());
 System.out.println("Artist    = " + track.getArtist().getName());
 System.out.println("Genre     = " + track.getGenre().getName());
}


Adding conditions: Restrictions

Example 1 - list of values

List users = session.createCriteria(User.class)
 .add( Restrictions.like("name", "Frank%") )
 .add( Restrictions.between("age", minAge, maxAge) )
 .list();

    
Example 2 - single value

Criteria criteria = session.createCriteria(User.class)
 .add(Restrictions.eq("id", new Long(1)));

User user = (User) criteria.uniqueResult();

            
Example 3 - Adding conditions: Restrictions    with native SQL

List users = sess.createCriteria(User.class)
 .add( Restrictions.sqlRestriction("lower({alias}.name) like lower(?)", "Frank%", Hibernate.STRING) )
 .list();

    
Limiting the amount of data returned: 

Criteria criteria = session.createCriteria(User.class)
 .addOrder(Order.asc("name"))
 .setFirstResult(0)
 .setMaxResults(10);

 List<User> users = criteria.list();
 for (User u : users) {
 System.out.println("User = " + u.getName());
 }


Using Projections

The class org.hibernate.criterion.Projections is a factory for Projection instances. You can apply a projection to a query in order to retrieve some special criteria such as max/min/average value for a field or, most important, for counting the number of records in a query:

Criteria criteria = session.createCriteria(User.class)
 .setProjection(Projections.max("age"));
 Integer maxAge = (Integer) criteria.uniqueResult();
 System.out.println("Max User age = " + maxAge);

 criteria.setProjection(Projections.min("age"));
 Integer minAge = (Integer) criteria.uniqueResult();
 System.out.println("Min User age = " + minAge);
 
 criteria.setProjection(Projections.avg("wage"));
 Double avgWage = (Double) criteria.uniqueResult();
 System.out.println("Avg User wage = " + avgWage);
 
 criteria.setProjection(Projections.sum("wage"));
 Integer totalWages = (Integer) criteria.uniqueResult();
 System.out.println("Total Users wages = " + totalWages);

How to count the number of records in a query:

Criteria criteria = session.createCriteria(User.class)
 .setProjection(Projections.rowCount());

 List result = criteria.list();
 if (!result.isEmpty()) {
 Integer rowCount = (Integer) result.get(0);
 System.out.println("Total Users: " + rowCount);
 }            

Follow us on Twitter