Wednesday, 11 July 2018

Hibernate Criteria Queries and Examples

               In previous post, we learned the  Hibernate Query Language(HQL) Examples.  In this post, we will discuss about the Criteria API of hibernate & it's usage with examples.

There are three way to fetch the data from the database in the Hibernate.
  • Using Session Interface - get() and load() methods  -limited control to accessing data
  • Using HQL(Hibernate Query Language) – Slightly more control using where clause and other clauses but it is more complicated to maintain in case of bigger queries with lots of clauses.
  • Using Criteria API

What is Criteria API ?


          The API (Application Programming Interface) of Hibernate Criteria provides an elegant way
 of building dynamic query on the persistence database.

          The hibernate criteria API is very Simplified API for fetching data from Criterion objects. The criteria API is an alternative of HQL (Hibernate Query Language) queries.  It is more powerful and flexible for writing tricky criteria functions and dynamic queries.

         The Criteria API allows you to build up a criteria query object programmatically.  The org.hibernate.Criteria interface defines the available methods for one of these objects. The Hibernate Session interface contains several createCriteria() methods.  Pass the persistent object’s class or its entity name to the createCriteria() method and Hibernate will create a Criteria object that returns instances of the persistence object’s class when your application executes a criteria query.

Examples:-


          The below is the simple example of Criteria API with no any restrictions or no any optional parameters, it will return the all the data of that entity class.            

Criteria criteria = session.createCriteria(Employee.class);
List<Employee> results = criteria.list();

Next example, we will see some examples of Restrictions.

Using Restrictions with Criteria:-


           The Criteria API makes it easy to use restrictions in your queries to selectively retrieve objects. You can add restrictions to a Criteria object with the add() method. The add() method takes an org.hibernate.criterion.Criterion object that represents an individual restriction. You can have more than one restriction for a criteria query.

  • Restrictions.eq() Example
       To retrieve objects that have a property value that “equals” your restriction, use the eq() method on Restrictions, as follows:

Criteria criteria= session.createCriteria(Employee.class);
criteria.add(Restrictions.eq("name","Anil"));
List<Employee> results = criteria.list();

It will fetch all employee's having name with Anil.

  •  Restrictions.ne() Example

       To retrieve objects that have a property value “not equal to” your restriction, use the ne() method on Restrictions, as follows:

Criteria criteria= session.createCriteria(Employee.class);
criteria.add(Restrictions.ne("name","Anil"));
List<Employee> results = criteria.list()

It will fetch all employee's except name with Anil.

  •  Restrictions.like() and Restrictions.ilike() Example

         Using like() and ilike() method of Restrictions, we can retrieve all objects that have a property matching part of a given pattern. It's kind of like and ilike clause of SQL. The ilike() method is case-insensitive.

Criteria criteria= session.createCriteria(Employee.class);
criteria.add(Restrictions.like("name","Mahesh%",MatchMode.ANYWHERE));
List<Employee> results = criteria.list();

org.hibernate.criterion.MatchMode object to specify how to match the specified value to the stored data. The MatchMode object  has four different matches:

ANYWHERE: Anyplace in the string
END: The end of the string
EXACT: An exact match
START: The beginning of the string.


  • Restrictions.isNull() and Restrictions.isNotNull() Example

      The isNull() and isNotNull() method of Restrictions is to search the null and not null value of the property.

Criteria criteria= session.createCriteria(Employee.class);
criteria.add(Restrictions.isNull("name"));
List<Employee> results = criteria.list();

The isNotNull() is same like isNull() but it will return the property having not null values.


  •  Restrictions.gt(), Restrictions.ge(), Restrictions.lt() and Restrictions.le() Examples

          Several of the restrictions are useful for doing math comparisons. The greater-than comparison is gt(), the greater-than-or-equal-to comparison is ge(), the less-than comparison is lt(), and the less-than-or-equal-to comparison is le().

Criteria crt= session.createCriteria(Employee.class);
crt.add(Restrictions.gt("age", 40));
List<Employee> results = crt.list();


Paging Through the ResultSet:--


        In SQL query, we can use Offset and limit for pagination but in Criteria API have methods setFirstResult(int arg) and setMaxResults(int arg). Using these two methods we can construct paging component in our application.

Criteria criteria = session.createCriteria(Employee.class);
criteria.setFirstResult(1);
criteria.setMaxResults(20);
List<Employee> results = criteria.list();

The above query paginate 20 records each page, you can change this to 10 or 5 by setting setMaxResults to 10 or 5.


Obtaining a Unique Result:--

       
           If you want obtain a single Object reference instead of a List, the uniqueResult() method on the Criteria object returns an object or null. If there is more than one result, the uniqueResult() method throws a HibernateException.

        The following example demonstrates having a result set that would have included more than one result, except that it was limited with the setMaxResults() method,

Criteria criteria = session.createCriteria(Employee.class);
Criterion age = Restrictions.gt("age", 40);
criteria.setMaxResults(1);
Employee employee = (Employee) criteria.uniqueResult();


Obtaining Distinct Results:--


        Hibernate Criteria provides a result transformer for distinct entities, 
org.hibernate.transform.DistinctRootEntityResultTransformer, which ensures that no duplicates will be in your query’s result set. Rather than using SELECT DISTINCT with SQL, the distinct result transformer compares each of your results using their default hashCode() methods, and only adds those results with unique hash codes to your result set.

Criteria criteria = session.createCriteria(Employee.class);
Criterion age = Restrictions.gt("age", 40);
criteria.setResultTransformer( DistinctRootEntityResultTransformer.INSTANCE )
List<Employee> results = criteria.list();

Sorting the Query’s Results using Order:--


        Sorting the query’s results works much the same way with criteria as it would with HQL or SQL. The Criteria API provides the org.hibernate.criterion.Order class to sort your result set in either ascending or descending order, according to one of your object’s properties.

The below example demonstrates how to use the Order in Criteria,

Criteria crt = session.createCriteria(Employee.class);
crt.add(Restrictions.gt("age", 30));
crt.addOrder(Order.desc("age"));
List<Employee> results = crt.list();

No comments:

Post a Comment