Hibernate Tutorial

Core Hibernate

Hibernate Mapping

Hibernate Annotations

Hibernate with Spring Framework

Hibernate with Database

Hibernate Log4j

Inheritance Mapping

Hibernate - Query Language

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but it operates on persistent objects, their properties, and classes rather than tables and columns. HQL provides a way to bridge the gap between the object-oriented domain model and the relational database.

In this tutorial, we will go through the basics of HQL.

1. Basics of HQL:

HQL allows you to express queries against objects defined in your Hibernate mappings. It abstracts away the nuances of individual databases, thus making your application more portable.

2. Simple Queries:

Select All Properties: To retrieve all properties of an object:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List<Employee> employees = query.list();

Select Specific Properties: You can retrieve specific properties and possibly return a list of Object[]:

String hql = "SELECT E.firstName, E.lastName FROM Employee E";
Query query = session.createQuery(hql);
List<Object[]> names = query.list();

3. Where Clause:

You can add conditions to your HQL queries:

String hql = "FROM Employee E WHERE E.id > 5";
Query query = session.createQuery(hql);
List<Employee> employees = query.list();

4. Pagination:

HQL supports pagination:

String hql = "FROM Employee";
Query query = session.createQuery(hql).setFirstResult(0).setMaxResults(10);
List<Employee> employees = query.list();

5. Order By:

Ordering results:

String hql = "FROM Employee E ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List<Employee> employees = query.list();

6. Named Parameters:

HQL supports named parameters:

String hql = "FROM Employee E WHERE E.firstName = :name";
Query query = session.createQuery(hql).setParameter("name", "John");
List<Employee> employees = query.list();

7. Aggregation:

HQL supports aggregate functions:

String hql = "SELECT COUNT(E) FROM Employee E";
Query query = session.createQuery(hql);
Long count = (Long) query.uniqueResult();

8. Joins:

You can write join queries in HQL:

// Assuming each employee has a department
String hql = "SELECT E.firstName, D.name FROM Employee E INNER JOIN E.department D";
Query query = session.createQuery(hql);
List<Object[]> results = query.list();

9. Update and Delete:

HQL supports updates and deletes:

// Update:
String hql = "UPDATE Employee set salary = :salary WHERE id = :id";
Query query = session.createQuery(hql).setParameter("salary", 50000).setParameter("id", 5);
int rowsAffected = query.executeUpdate();

// Delete:
hql = "DELETE FROM Employee WHERE id = :id";
query = session.createQuery(hql).setParameter("id", 5);
rowsAffected = query.executeUpdate();

10. Native SQL:

In situations where you need to write database-specific SQL queries, you can use native SQL with Hibernate:

List employees = session.createSQLQuery("SELECT * FROM Employee").list();

Conclusion:

HQL is a powerful querying language designed for Hibernate ORM. It allows developers to write database-independent queries, thereby improving the portability and maintainability of applications. While HQL covers most of the querying scenarios, Hibernate also supports native SQL and Criteria API for more advanced and specialized requirements.

  1. Executing HQL queries in Hibernate:

    • Execute HQL queries using the createQuery() method on the Session object.
    String hql = "FROM Employee";
    Query query = session.createQuery(hql);
    List<Employee> employees = query.list();
    
  2. HQL select statements in Hibernate:

    • Use HQL select statements to retrieve entities from the database.
    String hql = "SELECT e.name, e.salary FROM Employee e WHERE e.department = :dept";
    Query query = session.createQuery(hql);
    query.setParameter("dept", "IT");
    List<Object[]> results = query.list();
    
  3. Filtering and sorting with HQL in Hibernate:

    • Apply filters and sorting in HQL queries for more specific results.
    String hql = "FROM Product p WHERE p.price > :minPrice ORDER BY p.price DESC";
    Query query = session.createQuery(hql);
    query.setParameter("minPrice", 100.0);
    List<Product> products = query.list();
    
  4. Using parameters in HQL queries:

    • HQL queries support parameters for dynamic and reusable queries.
    String hql = "FROM Employee e WHERE e.department = :dept AND e.salary > :minSalary";
    Query query = session.createQuery(hql);
    query.setParameter("dept", "HR");
    query.setParameter("minSalary", 50000.0);
    List<Employee> employees = query.list();
    
  5. Joining tables with HQL in Hibernate:

    • Join tables using HQL to fetch related entities.
    String hql = "FROM Order o INNER JOIN FETCH o.customer WHERE o.totalAmount > :minAmount";
    Query query = session.createQuery(hql);
    query.setParameter("minAmount", 100.0);
    List<Order> orders = query.list();
    
  6. Aggregate functions in HQL:

    • Use aggregate functions in HQL to perform calculations on data.
    String hql = "SELECT AVG(e.salary) FROM Employee e WHERE e.department = :dept";
    Query query = session.createQuery(hql);
    query.setParameter("dept", "Finance");
    Double averageSalary = (Double) query.uniqueResult();
    
  7. Subqueries in Hibernate Query Language:

    • Use subqueries in HQL to create nested queries.
    String hql = "FROM Employee e WHERE e.salary > (SELECT AVG(e2.salary) FROM Employee e2)";
    Query query = session.createQuery(hql);
    List<Employee> highPaidEmployees = query.list();