Hibernate: Criteria API builds a query in type-safe pieces

Verbose, but it is the right tool when the conditions are not known until runtime.

Code
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Order> q = cb.createQuery(Order.class);
Root<Order> root = q.from(Order.class);

List<Predicate> where = new ArrayList<>();
if (status != null)  where.add(cb.equal(root.get("status"), status));
if (minTotal != null) where.add(cb.ge(root.get("total"), minTotal));

q.where(where.toArray(new Predicate[0]));
List<Order> result = em.createQuery(q).getResultList();
Output
Two optional filters produce four different SQL statements,
without any string concatenation.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11