Quick revision
The short answer
We get a CriteriaBuilder from the EntityManager, create a CriteriaQuery<Product> with a Root<Product>, and collect predicates in a list: a case-insensitive like on name only if a name was given, and a less-than-or-equal on price only if a maximum was given. Then we pass the list to where() and run the query; with no filters, the query returns every product. The static metamodel, Product_.name instead of the string "name", makes the attribute references type-safe.
What to remember
In this answer, we built a Criteria API query with optional filters. We created a CriteriaQuery and Root from the CriteriaBuilder, collected predicates in a list, adding a case-insensitive like on name and a less-than-or-equal on price only when each filter was given, and passed them to where(), which adds no where clause when the list is empty. We saw the SQL for each input, made attribute references type-safe with the static metamodel, and added stable sorting and paging.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We get a CriteriaBuilder from the EntityManager, create a CriteriaQuery<Product> with a Root<Product>, and collect predicates in a list: a case-insensitive like on name only if a name was given, and a less-than-or-equal on price only if a maximum was given. Then we pass the list to where() and run the query; with no filters, the query returns every product. The static metamodel, Product_.name instead of the string "name", makes the attribute references type-safe.
Why this question is asked
Search forms with optional filters are where string-built JPQL turns ugly: conditional where and and fragments, parameter maps kept in sync by hand, and the occasional SQL injection when someone concatenates a value. The Criteria API was designed for exactly this case: building a query from code, piece by piece. Interviewers ask for it to see that we can write it correctly from memory and handle the details, such as case-insensitive matching and empty filters. In this answer, we will recap the Criteria API's main types, write the query step by step, see the SQL for different inputs, make it type-safe with the static metamodel, and look at sorting and paging.
1A Quick Recap of the Criteria API
The Criteria API builds a query as Java objects instead of a string. Three types do most of the work. CriteriaBuilder is a factory for queries and expressions: comparisons, like, lower, and and or. CriteriaQuery<T> is the query itself, typed by its result. Root<T> is the entity in the from clause, the starting point for attribute paths such as p.get("price"). A Predicate is a boolean condition we can add to the where clause.
Because the query is built from objects, we can add conditions with plain if statements, and every value is bound as a parameter by the provider, never concatenated into the query text.
2Writing the Query Step by Step
Here is the full method. The entity Product has a name and a price.
Notice how each step maps to a part of the query. q.from() is the from clause. Each if adds a condition only when its filter was given. where() with several predicates combines them with and. And when the list is empty, where() with no predicates adds no where clause at all, so search(null, null) returns every product.
For the name, we lower both sides, cb.lower() on the column and toLowerCase() on the input, so Desk Lamp matches lamp. Using Locale.ROOT avoids surprises with languages whose case rules differ, such as Turkish. We also treat a blank name as no filter, which is usually what a search form means.
3What SQL Each Call Produces
Running the method with different inputs shows the query growing and shrinking with the filters.
- Create query and root
cb.createQuery(Product.class),q.from(Product.class) - Name given and not blank?Yesadd lower(name) like %name%Noskip
- Max price given?Yesadd price <= maxNoskip
- where(preds)empty list: no where clause
- Run the queryvalues bound as parameters
5 steps in order. Play them, or step through them one at a time.
Notice that the values always appear as bound parameters. Even though we built the like pattern by concatenating percent signs, the result is passed as a parameter, not inserted into the SQL text. If a user types a percent sign or underscore, it acts as a wildcard, though; when that matters we escape them and use the cb.like() overload that takes an escape character.
4Type Safety With the Static Metamodel
The string "name" in p.get("name") is checked only at runtime. If someone renames the attribute to title, the code still compiles and fails when the search runs. The static metamodel fixes that. An annotation processor, Hibernate's metamodel generator, creates a class Product_ with a typed field per attribute, and we use those fields instead of strings. The artifact name changed across Hibernate versions (hibernate-jpamodelgen, later hibernate-processor), so check your version.
Now a rename breaks the build instead of the search, and the compiler also checks the types: comparing price with a String would not compile.
5Adding Sorting and Paging
A real search also sorts and pages. Ordering is added with cb.asc() or cb.desc(), and paging is set on the executed query, not the criteria query.
Adding the id as a second sort key keeps the order stable when two products have the same price, so a product does not appear on two pages or on none.
6Follow-up questions
How would you write this with Spring Data?
With Specifications: each filter becomes a small Specification<Product>, for example nameContains(name) returning null when the name is empty, and the repository extends JpaSpecificationExecutor so we call findAll(spec, pageable). It is the same Criteria code, split into reusable pieces, with paging handled by Spring Data.
Why not just build a JPQL string with if statements?
It works for two filters, but each condition needs its own where or and handling, the parameters must be kept in sync with the string, and a careless concatenation risks injection. Criteria builds the structure and binds values for us.
Will lower(name) like '%lamp%' use an index?
Usually not. A leading wildcard prevents a normal B-tree index from being used, and lower() requires an expression index. For substring search on large tables, PostgreSQL's pg_trgm trigram index or a search engine is the right tool.
7Conclusion
In this answer, we built a Criteria API query with optional filters. We created a CriteriaQuery and Root from the CriteriaBuilder, collected predicates in a list, adding a case-insensitive like on name and a less-than-or-equal on price only when each filter was given, and passed them to where(), which adds no where clause when the list is empty. We saw the SQL for each input, made attribute references type-safe with the static metamodel, and added stable sorting and paging.
Open with
I would start with CriteriaBuilder cb from em.getCriteriaBuilder, then a CriteriaQuery of Product from cb.createQuery(Product.class), and a Root of Product from q.from(Product.class). Then I collect predicates in a list.
Then, if they want more
If the name is not null or blank, I add cb.like of cb.lower of p.get name, with the lowercased input wrapped in percent signs, so the match is case-insensitive. If the maximum price is not null, I add cb.le of p.get price and the max. Then q.select(p).where with the predicates converted to an array, and em.createQuery(q).getResultList().
If no filter is given, the list is empty and the query has no where clause, so it returns all products. All values are bound as parameters, so there is no injection risk, although a user's percent sign acts as a wildcard unless I escape it.
To make it type-safe I would use the static metamodel generated by Hibernate's annotation processor, so it is p.get(Product_.name) and a rename breaks the build instead of failing at runtime.
In a Spring Data project, I would usually split each filter into a Specification and call findAll with a Pageable, and add a stable order by price and id for paging.
About this answer
- Last updated
- 12 November 2026
- 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.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Write a Criteria API query that finds products with an optional name filter and an...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/74b713d6ad/