Hibernate Query Language (HQL) is a powerful and flexible query language that allows you to interact with a relational database using object-oriented syntax. HQL is a crucial component of Hibernate, as it enables you to retrieve and manipulate data stored in the database using Java objects and classes rather than writing raw SQL queries.
- Here’s an overview of Hibernate Query Language (HQL):
Basic Query Syntax:
- HQL queries resemble SQL queries but operate on Java objects and their properties. Instead of referring to database tables and columns, you work with Java class names and property names.
SELECT p FROM Product p WHERE p.category
= 'Electronics'
Select Statements:
- You can use SELECT statements in HQL to retrieve data from the database. The result of an HQL query can be a list of objects, a single object, or even scalar values.
Query query = session.createQuery
("FROM Product WHERE category = 'Electronics'");
List products = query.list();
Named Parameters:
- HQL supports named parameters, making it easier to write reusable queries with placeholders for parameter values.
Query query = session.createQuery
("FROM Product WHERE category = :category");
query.setParameter("category", "Electronics");
List products = query.list();
Joins:
- HQL supports various types of joins, including inner joins, left joins, and right joins, allowing you to retrieve data from multiple related tables.
SELECT o FROM Order o
JOIN FETCH o.customer
WHERE o.status = 'Shipped'
Aggregate Functions:
- You can use aggregate functions like SUM, COUNT, AVG, MIN, and MAX in HQL queries to perform calculations on database data.
Query query = session.createQuery
("SELECT COUNT(*) FROM Product");
Long productCount = (Long) query.uniqueResult();
Sorting:
- HQL queries can include ORDER BY clauses to sort the result set based on one or more properties.
Query query = session.createQuery
("FROM Product ORDER BY price DESC");
List products = query.list();
Aggregate Methods
- HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and following is the list of the available functions −
Sr.No. | Functionst | Description |
---|---|---|
1. | avg(property name) | The average of a property's value |
2. | count(property name or *) | The number of times a property occurs in the results |
3. | max(property name) | The maximum value of the property values |
4. | min(property name) | The minimum value of the property values |
5. | sum(property name) | The sum total of the property values |