Advertisement
Google Ad Slot: content-top
Hibernate Criteria API
The Criteria API is an alternative to HQL (Hibernate Query Language) for writing dynamic queries in Hibernate. Instead of writing queries as plain strings, Criteria API allows type-safe, object-oriented queries.
Why Use Criteria API?
✅ Dynamic Queries – Queries can be built at runtime.
✅ Type-Safe – Uses Java classes instead of raw strings.
✅ No String-Based HQL – Avoids syntax errors from misspelled query strings.
✅ Better Maintainability – Queries are constructed programmatically.
Setting Up Criteria API
To use Criteria API, you need to get a Session and use the CriteriaBuilder class.
Fetch All Records (Equivalent to SELECT * FROM table):
Applying WHERE Condition
🔹 Fetch Students with Age > 20
🔹 Equivalent SQL: SELECT * FROM student WHERE age > 20;
Applying Multiple Conditions (AND, OR)
🔹 Fetch Students where age > 20 AND name starts with 'A'
🔹 Equivalent SQL: SELECT * FROM student WHERE age > 20 AND name LIKE 'A%';
Sorting Results (ORDER BY)
🔹 Sort Students by Age (Ascending)
🔹 Equivalent SQL: SELECT * FROM student ORDER BY age ASC;
🔹 Sort Students by Name (Descending)
🔹 Equivalent SQL: SELECT * FROM student ORDER BY name DESC;
Fetching Specific Columns
🔹 Select Only Name and Age
🔹 Equivalent SQL: SELECT name, age FROM student;
Aggregation Functions (COUNT, SUM, AVG, MIN, MAX)
🔹 Count Total Students
🔹 Equivalent SQL: SELECT COUNT(*) FROM student;
🔹 Find Average Age
🔹 Equivalent SQL: SELECT AVG(age) FROM student;
Using Joins in Criteria API
🔹 Inner Join (Fetch Students with their Courses)
🔹 Equivalent SQL: SELECT * FROM student JOIN course ON student.id = course.student_id;
🔹 Left Join (Fetch Students Even If They Have No Courses)
🔹 Equivalent SQL: SELECT * FROM student LEFT JOIN course ON student.id = course.student_id;
Pagination (Limit & Offset)
Hibernate Criteria API allows pagination using setFirstResult() and setMaxResults().
🔹 Fetch Page 2 (5 Records Per Page)
🔹 Equivalent SQL: SELECT * FROM student LIMIT 5 OFFSET 5;
Deleting Data using Criteria API
🔹 Equivalent SQL: DELETE FROM student WHERE name = 'John';
Updating Data using Criteria API
🔹 Equivalent SQL: UPDATE student SET age = 25 WHERE name = 'Alice';