How to Use the Criteria API for Dynamic JPA Queries
Build dynamic JPA search queries with the Criteria API, the static metamodel and Spring Data Specifications, including paging, joins and the count query trap.

A search form with six optional filters has sixty four possible queries. Writing sixty four JPQL strings is out of the question, and concatenating one string by hand invites bugs, injection mistakes and a stray and at the wrong place. The Criteria API exists for this case. It builds a query as an object graph, so each filter adds a predicate only when the user supplied it. This post builds a product search in three steps, plain Criteria, the typed metamodel and Spring Data Specifications, then covers paging, joins and when a fixed JPQL query is the better answer. The related Hibernate query language features are in HQL features worth knowing.
The problem
A catalogue search accepts an optional category, a price range, a name fragment and an in stock flag. Each can be missing. The query must contain only the conditions that were provided.
package dev.javahacks.catalog;
import java.math.BigDecimal;
public record ProductFilter(
String category,
BigDecimal minPrice,
BigDecimal maxPrice,
String nameContains,
Boolean inStock) {}Plain Criteria
package dev.javahacks.catalog;
import jakarta.persistence.EntityManager;
import jakarta.persistence.criteria.*;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ProductSearch {
private final EntityManager em;
public ProductSearch(EntityManager em) {
this.em = em;
}
public List<Product> search(ProductFilter f) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Product> query = cb.createQuery(Product.class);
Root<Product> p = query.from(Product.class);
List<Predicate> where = new ArrayList<>();
if (f.category() != null) {
where.add(cb.equal(p.get("category"), f.category()));
}
if (f.minPrice() != null) {
where.add(cb.greaterThanOrEqualTo(p.get("price"), f.minPrice()));
}
if (f.maxPrice() != null) {
where.add(cb.lessThanOrEqualTo(p.get("price"), f.maxPrice()));
}
if (f.nameContains() != null && !f.nameContains().isBlank()) {
where.add(cb.like(cb.lower(p.get("name")), "%" + f.nameContains().toLowerCase() + "%"));
}
if (Boolean.TRUE.equals(f.inStock())) {
where.add(cb.greaterThan(p.get("quantity"), 0));
}
query.select(p).where(where.toArray(new Predicate[0])).orderBy(cb.asc(p.get("name")));
return em.createQuery(query).getResultList();
}
}Read it as three parts. CriteriaBuilder is the factory for expressions and predicates. Root<Product> is the from clause, the thing you navigate with p.get("price"). The list of predicates is the dynamic piece: an empty list yields where with no condition, which Hibernate omits, and a populated list is joined with and. Values are always bound as parameters, never concatenated into text, so the query is safe from SQL injection by construction, with the exception of the like pattern, where a literal % the user typed is still a wildcard, so escape it if that matters.
The weakness is the strings: p.get("price") is not checked by the compiler. Rename the field and the code compiles, then fails at run time with an IllegalArgumentException: Unable to locate Attribute with the given name [price].
The static metamodel
The fix is the static metamodel, a generated class that mirrors each entity with typed constants. Add the annotation processor, which in Hibernate 6.3 and later is called hibernate-processor:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-processor</artifactId>
<scope>provided</scope>
</dependency>Compile and you get Product_ in the same package with a field for each attribute: Product_.price, Product_.category, Product_.name. The predicates become checked by the compiler:
where.add(cb.equal(p.get(Product_.category), f.category()));
where.add(cb.greaterThanOrEqualTo(p.get(Product_.price), f.minPrice()));
where.add(cb.like(cb.lower(p.get(Product_.name)), "%" + f.nameContains().toLowerCase() + "%"));Rename price and the build fails at the exact line, which is the whole value of Criteria over string JPQL. The generated types also infer the attribute type, so passing a String to compare against price is a compile error.
Spring Data Specifications
A search method in a repository class works, but filters are rarely used in only one place. Spring Data wraps the Criteria predicate builder in a Specification, a reusable fragment you can combine. Extend JpaSpecificationExecutor on the repository:
public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {}package dev.javahacks.catalog;
import org.springframework.data.jpa.domain.Specification;
import java.math.BigDecimal;
public final class ProductSpecs {
private ProductSpecs() {}
public static Specification<Product> inCategory(String category) {
return (root, query, cb) -> category == null ? null : cb.equal(root.get(Product_.category), category);
}
public static Specification<Product> priceAtLeast(BigDecimal min) {
return (root, query, cb) -> min == null ? null : cb.greaterThanOrEqualTo(root.get(Product_.price), min);
}
public static Specification<Product> priceAtMost(BigDecimal max) {
return (root, query, cb) -> max == null ? null : cb.lessThanOrEqualTo(root.get(Product_.price), max);
}
public static Specification<Product> nameContains(String text) {
return (root, query, cb) -> text == null || text.isBlank()
? null
: cb.like(cb.lower(root.get(Product_.name)), "%" + text.toLowerCase() + "%");
}
public static Specification<Product> inStock(Boolean flag) {
return (root, query, cb) -> Boolean.TRUE.equals(flag) ? cb.greaterThan(root.get(Product_.quantity), 0) : null;
}
}A specification that returns null contributes no condition, which is the idiom that makes optional filters compose without if ladders. The service combines them:
public Page<Product> search(ProductFilter f, Pageable pageable) {
Specification<Product> spec = Specification
.where(ProductSpecs.inCategory(f.category()))
.and(ProductSpecs.priceAtLeast(f.minPrice()))
.and(ProductSpecs.priceAtMost(f.maxPrice()))
.and(ProductSpecs.nameContains(f.nameContains()))
.and(ProductSpecs.inStock(f.inStock()));
return products.findAll(spec, pageable);
}findAll(spec, pageable) runs the data query and, for a Page, the count query too, and it applies sorting from the Pageable, so a controller can accept ?sort=price,desc&page=2 and pass it through. In recent Spring Data versions Specification.where accepts a null argument, which is also why the first call is safe.
Joins, paging and the count trap
Real searches filter on related entities, for example products by supplier country. A join in a Specification needs care:
public static Specification<Product> suppliedFrom(String country) {
return (root, query, cb) -> {
if (country == null) return null;
Join<Product, Supplier> supplier = root.join(Product_.supplier, JoinType.INNER);
return cb.equal(supplier.get(Supplier_.country), country);
};
}A to-one join like this is safe. A join to a collection, say root.join(Product_.tags), multiplies rows: a product with three matching tags appears three times, and paging then counts the duplicates. Either add query.distinct(true) or, better, filter with a subquery or exists, which never multiplies rows. Do not combine a fetch join with pagination: Hibernate then logs HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory and loads every row into memory, the failure described in JOIN FETCH without duplicates.
The count query is a second trap. Spring Data derives it from the same specification, which is correct for a simple filter but wasteful when the main query selects with joins and ordering the count does not need. For a large table, a count over the full filter can be the slowest part of the page; consider returning a Slice, which fetches one extra row to learn whether a next page exists and skips the count entirely.
Choosing
| Situation | Use |
|---|---|
| Fixed query, known at compile time | JPQL with @Query |
| Optional filters, one repository | Specification composition |
| Many optional filters, full text, facets | A search tool such as Hibernate Search or a database index tailored to it |
| Heavy reporting with grouping and windows | A SQL layer, see Hibernate, JDBC and jOOQ for reports |
Criteria code is more verbose than the equivalent JPQL. If a query has three conditions that are always present, a @Query string is shorter, clearer and just as safe. Reserve Criteria and Specifications for the part of the application where the shape of the query really varies.
Testing dynamic queries
A query builder has many branches, and each filter combination is a path. Test each predicate alone and one test with everything on, against a real database so the generated SQL actually runs:
@DataJpaTest
@Testcontainers
class ProductSearchTest {
@Container @ServiceConnection
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");
@Autowired ProductRepository products;
@Test
void combinesOnlyTheFiltersThatWereSupplied() {
products.saveAll(List.of(
new Product("Java Book", "books", new BigDecimal("30.00"), 5),
new Product("Kotlin Book", "books", new BigDecimal("40.00"), 0),
new Product("Desk Lamp", "home", new BigDecimal("25.00"), 9)));
var spec = Specification.where(ProductSpecs.inCategory("books")).and(ProductSpecs.inStock(true));
assertThat(products.findAll(spec)).extracting(Product::getName).containsExactly("Java Book");
}
}Log the generated SQL once per specification while writing it, and check the where clause contains only what you expect; logging SQL and statement counts shows how.
Readability is the real cost
The most common complaint about the Criteria API is that it is hard to read, and it is fair. A query that takes one line in JPQL takes ten with a builder, and the structure of the query hides behind method calls. Two practices reduce the pain. Keep each predicate in a small named method, as the specifications do, so the search reads as a list of conditions like hasStatus and totalAtLeast. And log the generated SQL once when you write a new predicate, because the SQL is what the database runs and what you will tune. When a query stops changing shape, convert it back to a fixed JPQL string: static queries are validated at startup and simpler to review.
When this does not apply
If your filters are not on entity attributes but on computed values, window functions or full text matches, Criteria will fight you, and a native query or a search engine is the right tool. Applications that build queries from user supplied field names, such as an API that accepts ?filter=price>10, must whitelist the attribute names before passing them to root.get(...), otherwise a caller can probe any field. See the Jakarta Persistence specification on the Criteria API and the Spring Data JPA reference on Specifications.


