Menu

Criteria API

Criteria API

Building Queries in Code

The Criteria API builds queries with Java objects instead of strings. It is useful when filters change at runtime, such as in a search form where users fill in only some fields.

The old Hibernate-specific session.createCriteria() was removed in Hibernate 6. The current option is the Jakarta Persistence Criteria API shown here.

CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> query = cb.createQuery(Student.class);
Root<Student> root = query.from(Student.class);

query.select(root)
     .where(cb.equal(root.get("status"), Status.ACTIVE))
     .orderBy(cb.asc(root.get("name")));

List<Student> result = session.createQuery(query).getResultList();

Code Explanation:

  • CriteriaBuilder creates queries and conditions.
  • Root represents the entity in the from clause.
  • root.get("status") refers to a field by name, and a wrong name fails only at runtime.
  • where() and orderBy() add filtering and sorting.
  • session.createQuery(query) turns the criteria object into an executable query.

For dynamic filters, collect conditions in a list of Predicate objects and add only those that apply. To catch field name mistakes at compile time, generate the static metamodel using the hibernate-processor annotation processor.


Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details