Hibernate provides two powerful methods for querying data: HQL (Hibernate Query Language) and the Criteria API. Both methods allow you to interact with the database using object-oriented syntax instead of raw SQL queries. In this article, we will dive deep into both HQL and Criteria, demonstrating how to use them effectively for querying and manipulating data in Hibernate.
Hibernate Query Language (HQL) is an object-oriented query language that is used to query the database in a way that is independent of the underlying database and uses the entity class names instead of database table names.
import org.hibernate.Session; import org.hibernate.query.Query; import java.util.List; public class EmployeeService { public ListgetAllEmployees() { Session session = HibernateUtil.getSession(); session.beginTransaction(); String hql = "FROM Employee"; Query query = session.createQuery(hql, Employee.class); List employees = query.getResultList(); session.getTransaction().commit(); session.close(); return employees; } }
In this example, the HQL query "FROM Employee"
is used to fetch all records from the Employee
entity (which corresponds to the Employee
table in the database). The results are stored in a list of Employee
objects.
HQL also supports standard SQL-like constructs such as WHERE
, ORDER BY
, and GROUP BY
for filtering and organizing the results.
import org.hibernate.Session; import org.hibernate.query.Query; import java.util.List; public class EmployeeService { public ListgetEmployeesWithSalaryGreaterThan(double salary) { Session session = HibernateUtil.getSession(); session.beginTransaction(); String hql = "FROM Employee e WHERE e.salary > :salary"; Query query = session.createQuery(hql, Employee.class); query.setParameter("salary", salary); List employees = query.getResultList(); session.getTransaction().commit(); session.close(); return employees; } }
In this example, the HQL query uses a WHERE
clause to filter employees whose salary is greater than a specified value. The setParameter
method is used to bind the salary
value to the query.
HQL allows you to sort the results using the ORDER BY
clause. This is useful when you want to retrieve records in a specific order.
import org.hibernate.Session; import org.hibernate.query.Query; import java.util.List; public class EmployeeService { public ListgetEmployeesSortedByName() { Session session = HibernateUtil.getSession(); session.beginTransaction(); String hql = "FROM Employee e ORDER BY e.name"; Query query = session.createQuery(hql, Employee.class); List employees = query.getResultList(); session.getTransaction().commit(); session.close(); return employees; } }
In this example, the query orders the results by the name
field of the Employee
entity.
The Criteria API in Hibernate provides a programmatic approach to constructing queries. It is especially useful when building dynamic queries where the conditions are not fixed or known at compile time.
The Criteria API is part of the org.hibernate.criterion
package and offers a type-safe way of querying data using objects.
import org.hibernate.Session; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import java.util.List; public class EmployeeService { public ListgetAllEmployees() { Session session = HibernateUtil.getSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(Employee.class); List employees = criteria.list(); session.getTransaction().commit(); session.close(); return employees; } }
In this example, a Criteria
query is used to fetch all records from the Employee
entity. The createCriteria
method creates a new criteria object for the Employee
class, and the list()
method retrieves the results.
The Criteria API allows the use of Restrictions
to add conditions like equal
, greater than
, less than
, etc., to filter results.
import org.hibernate.Session; import org.hibernate.Criteria; import org.hibernate.criterion.Restrictions; import java.util.List; public class EmployeeService { public ListgetEmployeesWithSalaryGreaterThan(double salary) { Session session = HibernateUtil.getSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(Employee.class); criteria.add(Restrictions.gt("salary", salary)); List employees = criteria.list(); session.getTransaction().commit(); session.close(); return employees; } }
In this example, the Restrictions.gt
method adds a condition to the criteria query to retrieve employees with a salary greater than the specified value.
The Criteria API also supports projections, which are used to select specific columns (or fields) from an entity. This can improve performance when you only need a subset of the columns.
import org.hibernate.Session; import org.hibernate.Criteria; import org.hibernate.criterion.Projections; import java.util.List; public class EmployeeService { public List
In this example, a projection is used to retrieve only the name
and salary
fields from the Employee
entity, instead of the entire entity. The results are returned as an array of Object[]
where each element represents a column.
Both HQL and the Criteria API are powerful tools in Hibernate for querying data. While HQL provides a more SQL-like syntax, the Criteria API offers a type-safe, programmatic approach for constructing dynamic queries. Below are the differences between the two:
In this article, we have explored the two main querying mechanisms in Hibernate: HQL and the Criteria API. HQL allows for SQL-like querying using entity objects, while the Criteria API provides a type-safe, programmatic approach for dynamic queries. Both methods are essential tools in a Hibernate developer’s toolkit for working with relational databases in Java.