Wednesday, 11 July 2018

Hibernate Criteria Queries with Examples

In the previous post, we learned about Hibernate Query Language (HQL) with examples. In this post, we will discuss the Hibernate Criteria API, its features, and its usage with examples.

Hibernate provides three ways to retrieve data from a database:

  1. Using the Session interface (get() and load() methods) – These methods provide limited control over data retrieval and are primarily used to fetch entities by their primary key.

  2. Using HQL (Hibernate Query Language) – HQL provides more flexibility by supporting WHERE, ORDER BY, GROUP BY, and other clauses. However, HQL queries can become difficult to read and maintain as they grow in complexity.

  3. Using the Criteria API – The Criteria API allows you to build queries programmatically, making them easier to construct, maintain, and modify dynamically.


What is Criteria API ?


          The Hibernate Criteria API provides an elegant way to build dynamic queries for retrieving data from a database.

The Criteria API is a simplified, object-oriented alternative to Hibernate Query Language (HQL). It allows you to construct queries programmatically instead of writing HQL strings, making it more flexible and easier to maintain when building dynamic queries with complex conditions.

The org.hibernate.Criteria interface defines the methods used to create and execute criteria queries. The Hibernate Session interface provides the createCriteria() method, which accepts either a persistent class or its entity name. Hibernate then creates a Criteria object that returns instances of the specified entity class when the query is executed.

Example:-

The following example demonstrates a simple Criteria API query without any restrictions or optional parameters. It retrieves all records from the corresponding entity table.

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 Hibernate Criteria API makes it easy to add restrictions to queries and retrieve only the required objects. You can add restrictions to a Criteria object by using the add() method.

The add() method accepts an org.hibernate.criterion.Criterion object, which represents an individual query condition. A criteria query can contain one or more restrictions, allowing you to build complex queries by combining multiple conditions.

  • Restrictions.eq() Example
      To retrieve objects whose property value matches a specific value, use the eq() method provided by the Restrictions class, as shown below:

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 whose property value is not equal to a specified value, use the ne() method of the Restrictions class, as shown below:

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 the like() and ilike() methods of the Restrictions class, you can retrieve objects whose property values match a specified pattern. These methods are similar to the SQL LIKE clause.

The like() method performs a case-sensitive comparison, whereas the ilike() method performs a case-insensitive comparison.

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

          The Hibernate Criteria API provides several restriction methods for performing comparison operations. The gt() method is used for greater-than comparisons, ge() for greater-than-or-equal-to comparisons, lt() for less-than comparisons, and le() for less-than-or-equal-to comparisons.

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 to retrieve a single object instead of a List, you can use the uniqueResult() method of the Criteria object. This method returns a single object if exactly one result is found, or null if no matching record exists. If the query returns more than one result, uniqueResult() throws a HibernateException.

The following example demonstrates a query that would normally return multiple results. However, by using the setMaxResults() method, the result set is limited to a single record.

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