Advertise with us

Our eBooks

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("name", "Frank%") )
 .add( Restrictions.between("age", minAge, maxAge) )

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) )

Limiting the amount of data returned: 

Criteria criteria = session.createCriteria(User.class)

 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)
 Integer maxAge = (Integer) criteria.uniqueResult();
 System.out.println("Max User age = " + maxAge);

 Integer minAge = (Integer) criteria.uniqueResult();
 System.out.println("Min User age = " + minAge);
 Double avgWage = (Double) criteria.uniqueResult();
 System.out.println("Avg User wage = " + avgWage);
 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)

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

Please publish modules in offcanvas position.