Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Your team writes dynamic search with Criteria API code that has become hard to read and test. What alternatives and structuring approaches would you consider?

First I would restructure: make each filter its own small function that returns a predicate, ideally as Spring Data Specifications that compose with and, and test each one on its own. If the team wants fluent, type-safe queries, Querydsl or jOOQ read far better than raw Criteria code, and Hibernate's newer typed query features and Jakarta Data repositories may fit, depending on the versions we run. And if the search is very dynamic, with free text, fuzzy matching and many combinations, a search engine is a better home for it than SQL.

Why this question is asked

Criteria API code tends to start clean and grow into a single 300-line method with nested ifs, joins created in three places and a unit test nobody can read. The problem is rarely the API itself; it is that all the filters live in one place and can only be tested together. Interviewers ask this scenario to see whether we can improve structure before reaching for a new library, and whether we know the alternatives and their costs. In this answer, we will look at why the code became hard to work with, restructure it into small filters, express those as Specifications, compare Querydsl, jOOQ and newer Hibernate features, and decide when a search engine is the right answer.

1Why the Code Became Hard to Read

A typical dynamic search method gets a request object with ten optional fields and builds the whole query in one method. Each field adds an if, some add joins, and joins must not be added twice, so flags appear. The result is code where the query's shape is spread over the whole method and cannot be tested piece by piece.

Java
public List<Order> search(OrderSearch s) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Order> q = cb.createQuery(Order.class);
Root<Order> o = q.from(Order.class);
List<Predicate> ps = new ArrayList<>();
Join<Order, Customer> c = null;
if (s.customerName() != null) { c = o.join("customer"); ps.add(cb.like(c.get("name"), s.customerName() + "%")); }
if (s.country() != null) { if (c == null) c = o.join("customer"); ps.add(cb.equal(c.get("country"), s.country())); }
if (s.minTotal() != null) ps.add(cb.ge(o.get("total"), s.minTotal()));
// ... 12 more filters, 3 more joins, sorting, paging
q.where(ps.toArray(Predicate[]::new));
return em.createQuery(q).getResultList();
}

Notice the join flag for customer. Each new filter on a joined entity has to know about every other filter on it. That coupling, not the Criteria API's verbosity, is what makes the code hard to change.

2Restructure First: One Small Function Per Filter

The first improvement needs no new library. We give each filter its own function that takes the root and the builder and returns a predicate, or nothing when the filter is not set. Joins are obtained through a helper that reuses an existing join instead of creating a second one. The search method becomes a short list of filters combined with and.

Each filter can then be tested in isolation: one integration test per filter, against a small data set in a real database (for example with Testcontainers), asserting which rows it keeps. Testing against the real database matters, because the interesting bugs are in the SQL, such as case sensitivity, nulls and duplicates from joins, not in the Java.

3Spring Data Specifications

Spring Data JPA already gives us this structure. A Specification<T> is a function from root, query and builder to a predicate, and specifications compose with and and or. The repository extends JpaSpecificationExecutor and accepts a specification plus a Pageable.

Java
class OrderSpecs {
static Specification<Order> customerNameStarts(String prefix) {
return (o, q, cb) -> prefix == null ? null
: cb.like(cb.lower(customer(o).get(Customer_.name)), prefix.toLowerCase(Locale.ROOT) + "%");
}
static Specification<Order> country(String country) {
return (o, q, cb) -> country == null ? null : cb.equal(customer(o).get(Customer_.country), country);
}
static Specification<Order> minTotal(BigDecimal min) {
return (o, q, cb) -> min == null ? null : cb.ge(o.get(Order_.total), min);
}
@SuppressWarnings("unchecked")
private static Join<Order, Customer> customer(Root<Order> o) { // reuse the join if present
return (Join<Order, Customer>) o.getJoins().stream()
.filter(j -> j.getAttribute().equals(Order_.customer)).findFirst()
.orElseGet(() -> o.join(Order_.customer));
}
}
Page<Order> page = orders.findAll(
Specification.allOf(customerNameStarts(s.name()), country(s.country()), minTotal(s.minTotal())),
PageRequest.of(0, 20, Sort.by("createdAt").descending()));
// where lower(c.name) like 'ad%' and c.country = 'DE' and o.total >= 100 (nulls ignored)

A specification that returns null adds no condition, so unset filters disappear naturally. Each specification is a few lines, named after its business meaning, and reusable in other searches. The API for combining them has evolved across Spring Data versions, so check yours; allOf exists in current versions, and the older where(...).and(...) style is being replaced.

4Querydsl, jOOQ and Newer Hibernate Features

If the team finds Criteria code hard to read even when well structured, fluent query libraries help. Querydsl generates Q-classes from entities and reads almost like JPQL, and Spring Data integrates it through QuerydslPredicateExecutor; the original project has been slow to release, and many teams now use the OpenFeign fork, so check its maintenance status. jOOQ takes a different approach: it generates Java from the database schema and builds SQL, not JPQL, so it suits teams who want full SQL control, especially for complex reads, at the cost of leaving the entity model and, for some commercial databases, a licence.

Hibernate itself has newer options. Hibernate 6.3 and later can check HQL in annotations at compile time and generate typed query methods, and Hibernate 6.6 and 7 implement Jakarta Data repositories, a standard repository model with typed queries. These are newer and some parts are marked incubating, so check your version before building on them.

Java
// Querydsl: the same three filters
BooleanBuilder where = new BooleanBuilder();
if (s.name() != null) where.and(QOrder.order.customer.name.lower().startsWith(s.name().toLowerCase(Locale.ROOT)));
if (s.country() != null) where.and(QOrder.order.customer.country.eq(s.country()));
if (s.minTotal() != null) where.and(QOrder.order.total.goe(s.minTotal()));
Page<Order> page = orders.findAll(where, PageRequest.of(0, 20));
Options for dynamic search
OptionStrengthCost
Criteria, restructuredno new dependency, standard JPAstill verbose
Spring Data Specificationssmall reusable filters, paging built inCriteria code inside each one
Querydslfluent and type-safe over entitiescode generation, check fork maintenance
jOOQfull SQL control, type-safe from schemaleaves the entity model, possible licence
Hibernate typed queries, Jakarta Datastandard, compile-time checksnewer, partly incubating
Search enginefree text, facets, many filter combinationsseparate system, eventual consistency

5When the Answer Is a Search Engine

Sometimes the difficulty of the code reflects the difficulty of the problem. If users combine many filters freely, search text with typos, expect relevance ranking or want facet counts such as 120 results in Germany, 45 in France, a relational database struggles regardless of the query builder, because no set of indexes serves every combination. A search engine such as Elasticsearch or OpenSearch is built for that. We keep the database as the source of truth and feed the search index from it, for example with change events, accepting that the index is a second or two behind.

So the choice follows the requirements. A handful of structured filters on indexed columns stays in SQL, ideally as Specifications. Free-form, many-filter search moves to a search engine.

6Follow-up questions

How do you test a Specification?

With an integration test against a real database: insert a few rows that should and should not match, run findAll with only that specification, and assert the ids returned. One test per filter, plus a few for important combinations, keeps the suite small and clear.

Do Specifications avoid N+1 problems?

No. They only build the where clause. If the result entities have associations that the caller touches, we still need a fetch plan, such as an entity graph on the repository method, or a projection.

What about duplicates when filtering on a collection?

A filter on a to-many association, such as orders containing a product, joins the collection and can repeat the root. Use an exists subquery in that specification, or query.distinct(true), and check the count query that paging runs.

7Conclusion

In this answer, we treated hard-to-read Criteria code mainly as a structure problem. We split the search into one small function per filter, expressed those as composable Spring Data Specifications with shared joins and tested each in isolation against a real database. We compared fluent alternatives such as Querydsl and jOOQ and the newer Hibernate typed query and Jakarta Data features, and saw that very dynamic, free-form search belongs in a search engine fed from the database.

What to say in the interviewAbout 90 seconds aloud

Open with

I would first fix the structure, because the usual problem is not the Criteria API but one huge method where every filter knows about every join. I would make each filter its own small function that returns a predicate or null when the filter is not set, with a helper that reuses joins.

Then, if they want more

In Spring Data that is exactly what Specifications are: each filter becomes a named Specification, they compose with allOf or and, and the repository's findAll takes the specification and a Pageable.

Then each filter gets its own integration test against a real database with Testcontainers, which is where the real bugs show up, like case sensitivity, nulls and duplicate rows from joins.

If the team still finds Criteria code hard to read, I would consider Querydsl, which gives fluent, type-safe queries over the entities, checking the state of the fork they use, or jOOQ if they want full SQL control, accepting it leaves the entity model.

Newer Hibernate versions also offer compile-time checked queries and Jakarta Data repositories, which I would evaluate depending on our version.

Finally, if the search is truly dynamic, with free text, typos, ranking or facets across many fields, I would move it to Elasticsearch or OpenSearch fed from the database, because no query builder fixes a problem that relational indexes cannot serve.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your team writes dynamic search with Criteria API code that has become hard to read and...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/cab7abb802/