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.
✅ 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.
To use Criteria API, you need to get a Session
and use the CriteriaBuilder
class.
SELECT * FROM table
):WHERE
Condition🔹 Fetch Students with Age > 20
🔹 Equivalent SQL: SELECT * FROM student WHERE age > 20;
AND
, OR
)🔹 Fetch Students where age > 20 AND name starts with 'A'
🔹 Equivalent SQL: SELECT * FROM student WHERE age > 20 AND name LIKE 'A%';
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;
🔹 Select Only Name and Age
🔹 Equivalent SQL: SELECT name, age FROM student;
🔹 Count Total Students
🔹 Equivalent SQL: SELECT COUNT(*) FROM student;
🔹 Find Average Age
🔹 Equivalent SQL: SELECT AVG(age) FROM student;
🔹 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;
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;
🔹 Equivalent SQL: DELETE FROM student WHERE name = 'John';
🔹 Equivalent SQL: UPDATE student SET age = 25 WHERE name = 'Alice';