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:
Using the
Sessioninterface (get()andload()methods) – These methods provide limited control over data retrieval and are primarily used to fetch entities by their primary key.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.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 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:-
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
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
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
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:--
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:--
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:--
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:--
Criteria crt = session.createCriteria(Employee.class); crt.add(Restrictions.gt("age", 30)); crt.addOrder(Order.desc("age")); List<Employee> results = crt.list();
The few more methods like Projections and Aggregates, those I have not covered. If you any doubt, put it in comment section of post.
Related Posts:--
1) Hibernate Query Language(HQL) Examples
2) What is a Hibernate Caching ? Explain first level and second level cache in Hibernate
3) What are different states of an entity bean in Hibernate?
4) What are the Core Interfaces of Hibernate framework ?
5) Hibernate One to One Mapping Example - Annotation based
No comments:
Post a Comment