Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Hibernate Criteria and HQL (Hibernate Query Language)


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.

1. Introduction to HQL (Hibernate Query Language)

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.

Example: Simple HQL Query

            import org.hibernate.Session;
            import org.hibernate.query.Query;
            import java.util.List;

            public class EmployeeService {
                public List getAllEmployees() {
                    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.

2. HQL Query with WHERE Clause

HQL also supports standard SQL-like constructs such as WHERE, ORDER BY, and GROUP BY for filtering and organizing the results.

Example: HQL Query with WHERE Clause

            import org.hibernate.Session;
            import org.hibernate.query.Query;
            import java.util.List;

            public class EmployeeService {
                public List getEmployeesWithSalaryGreaterThan(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.

3. HQL Query with ORDER BY Clause

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.

Example: HQL Query with ORDER BY Clause

            import org.hibernate.Session;
            import org.hibernate.query.Query;
            import java.util.List;

            public class EmployeeService {
                public List getEmployeesSortedByName() {
                    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.

4. Introduction to Criteria API

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.

Example: Simple Criteria Query

            import org.hibernate.Session;
            import org.hibernate.Criteria;
            import org.hibernate.criterion.Restrictions;
            import java.util.List;

            public class EmployeeService {
                public List getAllEmployees() {
                    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.

5. Criteria API with Restrictions

The Criteria API allows the use of Restrictions to add conditions like equal, greater than, less than, etc., to filter results.

Example: Criteria Query with Restrictions

            import org.hibernate.Session;
            import org.hibernate.Criteria;
            import org.hibernate.criterion.Restrictions;
            import java.util.List;

            public class EmployeeService {
                public List getEmployeesWithSalaryGreaterThan(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.

6. Criteria API with Projection

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.

Example: Criteria Query with Projection

            import org.hibernate.Session;
            import org.hibernate.Criteria;
            import org.hibernate.criterion.Projections;
            import java.util.List;

            public class EmployeeService {
                public List getEmployeeNamesAndSalaries() {
                    Session session = HibernateUtil.getSession();
                    session.beginTransaction();
                    Criteria criteria = session.createCriteria(Employee.class);
                    criteria.setProjection(Projections.projectionList()
                            .add(Projections.property("name"))
                            .add(Projections.property("salary")));
                    List results = criteria.list();
                    session.getTransaction().commit();
                    session.close();
                    return results;
                }
            }
        

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.

7. HQL vs. Criteria API

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:

Conclusion

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.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java