What is the Criteria API in Hibernate?

The Criteria API is Hibernate's programmatic, type-safe way to build queries by composing Java objects instead of writing HQL or SQL strings, which is useful for constructing dynamic queries whose conditions vary at runtime.

Key Points: • Queries are built by chaining method calls on a CriteriaBuilder and CriteriaQuery rather than concatenating query strings. • It's well suited to search screens where filters are optional and combined conditionally based on user input. • The JPA Criteria API (javax.persistence.criteria / jakarta.persistence.criteria) is the modern, standardized version most Hibernate applications use today. • Being type-safe, it catches many mistakes at compile time that a string-based HQL query would only surface at runtime. • It integrates with the JPA metamodel (generated _ classes) for fully type-checked attribute references.

Example: A product search form where a user may optionally filter by category, price range, or name benefits from the Criteria API, since predicates can be added to the query only when the corresponding filter was actually supplied.

Code Example:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Product> cq = cb.createQuery(Product.class);
Root<Product> root = cq.from(Product.class);

List<Predicate> predicates = new ArrayList<>();
if (category != null) {
    predicates.add(cb.equal(root.get("category"), category));
}
cq.where(predicates.toArray(new Predicate[0]));
List<Product> results = entityManager.createQuery(cq).getResultList();

Interview Tip: A concise interview answer is:

"The Criteria API lets me build queries programmatically using Java objects instead of query strings, which is especially useful for dynamic search filters where conditions are added conditionally at runtime, and it gives compile-time type safety that HQL strings don't."