Advertisement
Google Ad Slot: content-top
Hibernate Query Language
Hibernate Query Language (HQL) is an object-oriented query language similar to SQL, but designed for Hibernate. It operates on entity objects instead of database tables.
Select All Records:
- Equivalent to:
SELECT * FROM student; - Uses entity name (
Student) instead of table name.
Select Specific Columns:
- Returns specific fields instead of full entity objects.
HQL with WHERE Clause:
- Uses
:parameterto prevent SQL injection. - Equivalent SQL:
SELECT * FROM student WHERE name = 'Alice';
Ordering Results:
ORDER BY
- Sorts results alphabetically by name.
ORDER BY DESC
- Sorts by age in descending order.
Filtering with LIKE (Pattern Matching):
- Fetches all students whose names start with 'A'.
HQL Joins:
Inner Join
- Fetches students enrolled in Java course.
Left Join
- Includes students even if they don’t have courses.
Fetch Join (Eager Loading)
- Prevents LazyInitializationException by eagerly fetching related entities.
Aggregation Functions (COUNT, SUM, AVG, MIN, MAX):
Count Total Students
Find Sum Age
Find Average Age
Find Minimum Age
Find Maximum Age
Updating Data in HQL:
- Equivalent SQL:
UPDATE student SET age = 25 WHERE name = 'Alice';
Deleting Data in HQL:
- Equivalent SQL:
DELETE FROM student WHERE name = 'Bob';
Pagination in HQL:
Hibernate allows pagination using setFirstResult() and setMaxResults().
Named Queries (@NamedQuery):
- A Named Query allows you to define HQL queries inside entity classes.
- Benefits: Code is cleaner & easier to maintain.