Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท HQL, Criteria and Native Queries

The Criteria API: Building Queries in Java

Build queries with the JPA Criteria API and Hibernate's HibernateCriteriaBuilder - predicates, dynamic filters, the metamodel and when to prefer it over HQL, with a runnable builder stand-in.

HQL strings are easy to read, but they are only checked when the query runs. A typo in a field name becomes a runtime exception. The Criteria API builds the same query from Java objects instead: the compiler checks the structure, and you can add conditions with ordinary if statements. It shines for dynamic search forms where the user may fill in any combination of filters.

Criteria is also more verbose. A good rule: write fixed queries in HQL (or as named queries) and reach for Criteria when the shape of the query changes at runtime.

Hibernate is not available in the sandbox, so the Criteria code is read-only. The runnable examples implement a small predicate builder with JDBC and H2 to show the technique: collect optional conditions, combine them, and bind values safely.

Your first criteria query

The standard JPA entry point is CriteriaBuilder. In Hibernate 6.3+ you can use the richer HibernateCriteriaBuilder (a subtype) from the SessionFactory.

Java
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Book> query = cb.createQuery(Book.class);
Root<Book> book = query.from(Book.class);

query.select(book)
     .where(cb.lessThan(book.get("price"), new BigDecimal("20")))
     .orderBy(cb.asc(book.get("title")));

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

The pieces map directly to HQL:

Criteria HQL
query.from(Book.class) from Book b
query.select(book) select b
cb.lessThan(book.get("price"), x) b.price < :x
cb.and(p1, p2) / cb.or(p1, p2) p1 and p2 / p1 or p2
book.join("author") join b.author
cb.count(book), cb.avg(...) count(b), avg(...)

Values such as new BigDecimal("20") are turned into bind parameters automatically.

The metamodel: no more string field names

book.get("price") still uses a string. The JPA static metamodel generator (the hibernate-jpamodelgen annotation processor) creates a class Book_ with typed attributes at compile time:

Java
query.where(cb.lessThan(book.get(Book_.price), new BigDecimal("20")));

Now renaming price breaks the build instead of production, and the compiler checks that price is a BigDecimal. With the metamodel, Criteria queries are as refactoring-safe as plain Java.

Dynamic filters

Imagine a book search with optional title, maximum price and author. With HQL you would stitch strings together. With Criteria you collect predicates:

Java
public List<Book> search(String title, BigDecimal maxPrice, String author) {
    CriteriaBuilder cb = session.getCriteriaBuilder();
    CriteriaQuery<Book> q = cb.createQuery(Book.class);
    Root<Book> book = q.from(Book.class);
    Join<Book, Author> a = book.join(Book_.author, JoinType.LEFT);

    List<Predicate> filters = new ArrayList<>();
    if (title != null && !title.isBlank()) {
        filters.add(cb.like(cb.lower(book.get(Book_.title)), "%" + title.toLowerCase() + "%"));
    }
    if (maxPrice != null) {
        filters.add(cb.lessThanOrEqualTo(book.get(Book_.price), maxPrice));
    }
    if (author != null) {
        filters.add(cb.equal(a.get(Author_.name), author));
    }

    q.select(book).where(filters.toArray(Predicate[]::new)).orderBy(cb.asc(book.get(Book_.title)));
    return session.createQuery(q).getResultList();
}

where(Predicate...) joins the array with and, and an empty array means "no filter". This is the pattern to remember. The runnable version below uses the same idea with a minimal builder:

Java A dynamic predicate builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Real Criteria does the same job, but builds an object tree that Hibernate translates once, with the metamodel keeping names type-safe.

Joins, projections and pagination

Java
// tuple projection
CriteriaQuery<Tuple> q = cb.createTupleQuery();
Root<Book> b = q.from(Book.class);
q.multiselect(b.get(Book_.title).alias("title"), b.get(Book_.price).alias("price"));
List<Tuple> rows = session.createQuery(q).getResultList();
String title = rows.get(0).get("title", String.class);

// DTO via a constructor
CriteriaQuery<BookSummary> dto = cb.createQuery(BookSummary.class);
Root<Book> r = dto.from(Book.class);
dto.select(cb.construct(BookSummary.class, r.get(Book_.title), r.get(Book_.price)));

// paging, same as HQL
session.createQuery(q).setFirstResult(40).setMaxResults(20).getResultList();

For a page of results you usually also need the total number of rows. That takes a second query: cb.createQuery(Long.class) with cb.count(root) and the same predicates. Build the predicate list once in a helper and apply it to both queries.

Fetch joins and the typesafe dream

root.fetch(Book_.author) is the Criteria equivalent of join fetch. Do not use fetch in a count query (it breaks the aggregate) and avoid fetching collections together with setMaxResults.

Hibernate's HibernateCriteriaBuilder adds things the standard lacks: ilike, coalesce-style helpers, set operations (union, intersect), window functions and CTEs. Cast with session.getCriteriaBuilder() (it already returns a HibernateCriteriaBuilder in Hibernate 6.3+).

Other options for dynamic queries

Criteria is not the only choice:

  • Spring Data Specifications wrap Criteria predicates in reusable objects (spec1.and(spec2)).
  • Query by Example matches an entity probe's non-null fields (simple, limited).
  • Querydsl or jOOQ give a fluent typed API outside the JPA standard.
  • Hibernate's own SelectionSpecification (Hibernate 7) builds restrictions and ordering on top of an HQL string, a good middle ground between strings and Criteria.

Pick one style per project and keep the query code in repository classes, so changes stay in one place.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When is the Criteria API the best fit?

    Criteria composes predicates with normal Java code, which is ideal when filters are optional. Fixed queries are shorter in HQL.
  2. 2. What does the JPA static metamodel (Book_) give you?

    Generated classes such as Book_.price are typed, so renames and type mistakes are caught by the compiler.
  3. 3. What does where(predicates) do with an empty predicate array?

    An empty conjunction is true, so all rows match. That is why the collect-then-apply pattern works for optional filters.
  4. 4. How do you get a total row count for a paged Criteria search?

    A page contains only a slice. The total comes from a separate cb.count query that reuses the predicates.

Summary

  • Criteria builds queries from Java objects: CriteriaBuilder, CriteriaQuery, Root, Predicate.
  • The static metamodel replaces string attribute names with typed constants.
  • Collect optional predicates in a list and pass them to where(...) for dynamic search.
  • Use a second count query for totals, and keep fixed queries in HQL.

Next: Native SQL, Named Queries and Projections