Optional filters with Specifications
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)The admin customer search has three optional boxes: name, email and city. Users fill any of them, so the query must use only the boxes they filled, without a separate method for every combination.
Why findBy methods explode with optional filters
An optional filter is a search field the user may leave empty. Only the filled fields become conditions; the empty ones must not change the result.
With derived findBy methods, every combination of filters needs its own method, as the code starts to show.
// name only, email only, city only, and every combination...Page<Customer> findByFullNameContainingIgnoreCase(String name, Pageable p);Page<Customer> findByEmailContainingIgnoreCase(String email, Pageable p);Page<Customer> findByFullNameContainingIgnoreCaseAndEmailContainingIgnoreCase( String name, String email, Pageable p);Page<Customer> findByFullNameContainingIgnoreCaseAndAddressesCityIgnoreCase( String name, String city, Pageable p);// ... 3 filters = 7 methods plus "no filter"; 5 filters = 31 methods// and the service needs an if/else chain to pick oneThree filters give 7 combinations plus "no filter", and 5 filters give 31. Each method name grows longer, and the service needs an if/else ladder to pick the right one. One more filter doubles the work.
A single @Query with (:name is null or ...) for every filter avoids the explosion, and the Transactions module's ShopLite used one. The query becomes one long string that cannot be reused or combined, and joins for optional filters are hard to write that way.
JpaSpecificationExecutor and Specification<Customer> lambdas
Specification<T> is one reusable WHERE condition written as a lambda (root, query, cb) -> predicate. You keep each condition in a small static method and combine only the ones you need.
Add JpaSpecificationExecutor<Customer> to the repository, then write each condition as a small static method.
Example 1 · CustomerRepository.java and CustomerSpecs.java
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.customer;
import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface CustomerRepository extends JpaRepository<Customer, Integer>, JpaSpecificationExecutor<Customer> {}
package com.shoplite.customer;
import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.Join;import jakarta.persistence.criteria.Root;import jakarta.persistence.criteria.Subquery;
/** Small, reusable customer filters. Each one becomes one WHERE condition. */public final class CustomerSpecs {
private CustomerSpecs() { }
public static Specification<Customer> nameContains(String text) { return (root, query, cb) -> cb.like(cb.lower(root.get("fullName")), "%" + text.toLowerCase() + "%"); }
public static Specification<Customer> emailContains(String text) { return (root, query, cb) -> cb.like(cb.lower(root.get("email")), "%" + text.toLowerCase() + "%"); }
/** Version 1: a plain join. One SQL row per matching ADDRESS, not per customer. */ public static Specification<Customer> hasAddressInJoin(String city) { return (root, query, cb) -> { Join<Customer, Address> address = root.join("addresses"); return cb.equal(cb.lower(address.get("postalAddress").get("city")), city.toLowerCase()); }; }
/** Version 2: the join plus DISTINCT. */ public static Specification<Customer> hasAddressInDistinct(String city) { return (root, query, cb) -> { query.distinct(true); Join<Customer, Address> address = root.join("addresses"); return cb.equal(cb.lower(address.get("postalAddress").get("city")), city.toLowerCase()); }; }
/** Version 3: EXISTS (subquery). No join in the main query, so no duplicates. */ public static Specification<Customer> hasAddressIn(String city) { return (root, query, cb) -> { Subquery<Integer> sub = query.subquery(Integer.class); Root<Address> address = sub.from(Address.class); sub.select(cb.literal(1)) .where(cb.equal(address.get("customer"), root), cb.equal(cb.lower(address.get("postalAddress").get("city")), city.toLowerCase())); return cb.exists(sub); }; }}(no output: Examples 2 and 3 use these specifications)
What this code does
- The repository extends
JpaSpecificationExecutor<Customer>next toJpaRepository; no query methods are needed for the search. nameContainsandemailContainslower-case both sides and wrap the text in%...%.- The three city versions differ only in how they reach the addresses: a plain join, a join with
distinct, and anEXISTSsubquery.
JpaSpecificationExecutor adds findAll(Specification, Pageable), findAll(Specification, Sort), count(Specification) and exists(Specification). The three lambda parameters come from the JPA Criteria API: root is the entity in the FROM clause (root.get("fullName") is a property), query is the whole query (for distinct or subqueries), and cb, the CriteriaBuilder, builds conditions: cb.like, cb.equal, cb.lower, cb.isNull, cb.greaterThanOrEqualTo.
Give each static method a clear name in a small class such as CustomerSpecs. The service then reads like the screen: name contains, email contains, lives in.
Composing filters with and(), skipping null filters
Specification.unrestricted() is the starting point of a search: a specification that means "no condition". You add one specification with and(...) for each filter the user filled in, and skip the empty ones.
Start from "no condition", then add one condition per filled box. Example 2 shows AND, skipped filters and OR.
Example 2 · lab/CustomerSearchDemo.java: AND, skipped filters, OR
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.Page;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.data.jpa.domain.Specification;import org.springframework.stereotype.Component;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;import com.shoplite.customer.CustomerSpecs;
@Component("spec")class CustomerSearchDemo implements LabDemo {
private final CustomerRepository customers;
CustomerSearchDemo(CustomerRepository customers) { this.customers = customers; }
/** Start with "no condition" and add one Specification per filter that has a value. */ static Specification<Customer> search(String name, String email) { Specification<Customer> spec = Specification.unrestricted(); if (name != null && !name.isBlank()) { spec = spec.and(CustomerSpecs.nameContains(name.strip())); } if (email != null && !email.isBlank()) { spec = spec.and(CustomerSpecs.emailContains(email.strip())); } return spec; }
@Override public void run() { PageRequest first = PageRequest.of(0, 20, Sort.by("id")); print("name=ar", customers.findAll(search("ar", null), first)); print("name=ar, email=sharma", customers.findAll(search("ar", "sharma"), first)); print("no filters, page of 3", customers.findAll(search(null, " "), PageRequest.of(0, 3, Sort.by("id"))));
Specification<Customer> khanOrNair = CustomerSpecs.nameContains("khan").or(CustomerSpecs.nameContains("nair")); print("khan or nair", customers.findAll(khanOrNair, first)); }
static void print(String label, Page<Customer> page) { System.out.println(label + " -> " + page.getContent().stream().map(Customer::getFullName).toList() + " total=" + page.getTotalElements()); }}$ java -jar target/page-lab-0.1.0.jar --demo=spec DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where lower(c1_0.full_name) like ? escape '' order by c1_0.customer_id limit ?,? name=ar -> [Ravi Kumar, Priya Sharma, Arjun Mehta] total=3 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where lower(c1_0.full_name) like ? escape '' and lower(c1_0.email) like ? escape '' order by c1_0.customer_id limit ?,? name=ar, email=sharma -> [Priya Sharma] total=1 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 no filters, page of 3 -> [Asha Rao, Ravi Kumar, Meena Iyer] total=8 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where lower(c1_0.full_name) like ? escape '' or lower(c1_0.full_name) like ? escape '' order by c1_0.customer_id limit ?,? khan or nair -> [Divya Nair, Imran Khan] total=2
What this code does
search("ar", null)adds only the name condition; with"sharma"as well, both are joined withand.search(null, " ")adds nothing: no WHERE, a page of 3, and a COUNT because the page is full.escape ''in the log means no escape character was given: a%typed by a user would act as a wildcard.
spec.and(other) joins two specifications with AND, and or(...) with OR. With no filters at all, the query has no WHERE and returns every customer, page by page; Spring Data still adds ORDER BY, LIMIT and, when needed, a COUNT with the same WHERE.
Two details matter in real searches. Use cb.lower(...) with a lower-case pattern, so the search ignores case on any database. And escape % and _ typed by the user, or a search for % matches everyone; the ShopLite project shows the escaping.
Order of execution
Build the search
Tap the steps in the order the service runs them.
Specification.unrestricted() and the simpler PredicateSpecification; older code starts with Specification.where(null), which is deprecated now.Joins in a Specification and duplicate rows
An EXISTS subquery asks "does at least one matching row exist?" without joining. In a Specification, cb.exists(...) keeps one row per customer, so a customer with two Bengaluru addresses is counted once.
A join returns one row per address, so a customer with two matching addresses appears twice. Example 3 shows both fixes.
Example 3 · lab/CityFilterDemo.java: join, distinct and EXISTS
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.customer.CustomerRepository;import com.shoplite.customer.CustomerSpecs;
@Component("specjoin")class CityFilterDemo implements LabDemo {
private final CustomerRepository customers;
CityFilterDemo(CustomerRepository customers) { this.customers = customers; }
@Override public void run() { // Asha (id 1) has TWO addresses in Bengaluru: Home and Work. Pages of 1 make the problem visible. PageRequest page0 = PageRequest.of(0, 1, Sort.by("id")); PageRequest page1 = PageRequest.of(1, 1, Sort.by("id"));
CustomerSearchDemo.print("join, page 0", customers.findAll(CustomerSpecs.hasAddressInJoin("bengaluru"), page0)); CustomerSearchDemo.print("join, page 1", customers.findAll(CustomerSpecs.hasAddressInJoin("bengaluru"), page1)); CustomerSearchDemo.print("distinct, page 0", customers.findAll(CustomerSpecs.hasAddressInDistinct("bengaluru"), page0)); CustomerSearchDemo.print("exists, page 0", customers.findAll(CustomerSpecs.hasAddressIn("bengaluru"), page0)); }}$ java -jar target/page-lab-0.1.0.jar --demo=specjoin DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? join, page 0 -> [Asha Rao] total=2 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? join, page 1 -> [Asha Rao] total=2 DEBUG org.hibernate.SQL : select distinct c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select distinct count(distinct c1_0.customer_id) from customers c1_0 join addresses a1_0 on c1_0.customer_id=a1_0.customer_id where lower(a1_0.city)=? distinct, page 0 -> [Asha Rao] total=1 DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where exists(select 1 from addresses a1_0 where a1_0.customer_id=c1_0.customer_id and lower(a1_0.city)=?) order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 where exists(select 1 from addresses a1_0 where a1_0.customer_id=c1_0.customer_id and lower(a1_0.city)=?) exists, page 0 -> [Asha Rao] total=1
What this code does
- With the plain join, the COUNT counts address rows: total 2 for one customer, and page 1 shows Asha a second time.
query.distinct(true)givesselect distinctandcount(distinct ...): total 1.- The
EXISTSversion has no join in the main query, so the plain COUNT is already right.
root.join("addresses") lets a condition use city. Asha has two addresses in Bengaluru (Home and Work), so the joined query returns her twice. Hibernate 7 removes the duplicate entity from a single list, which hides the bug; paging exposes it: the COUNT says 2, and page 1 of size 1 shows Asha again.
There are two fixes. query.distinct(true) makes both the SELECT and the COUNT distinct. The cb.exists(...) subquery ("has at least one address in this city") never multiplies rows at all, and is what ShopLite uses for its city filter.
Query by Example as a lighter alternative
Query by Example (QBE) searches with a sample object: fill only the fields you want to match and leave the rest null. Every non-null field becomes one condition, all joined with AND.
Use a sample Customer as the search form. Example 4 searches with one.
Example 4 · lab/QueryByExampleDemo.java: search with a sample Customer
Runs in: the page-lab practice project (Spring Boot 4.1 with the ShopLite database)
package com.shoplite.lab;
import java.util.List;
import org.springframework.data.domain.Example;import org.springframework.data.domain.ExampleMatcher;import org.springframework.data.domain.PageRequest;import org.springframework.data.domain.Sort;import org.springframework.stereotype.Component;
import com.shoplite.customer.Customer;import com.shoplite.customer.CustomerRepository;
@Component("qbe")class QueryByExampleDemo implements LabDemo {
private final CustomerRepository customers;
QueryByExampleDemo(CustomerRepository customers) { this.customers = customers; }
@Override public void run() { // Text fields: "contains", ignoring case. Null fields are left out of the WHERE. ExampleMatcher matcher = ExampleMatcher.matching() .withIgnoreCase() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
Customer probe = new Customer("SHARMA", null, null); // fullName, email, phone List<Customer> found = customers.findAll(Example.of(probe, matcher), Sort.by("id")); System.out.println("name has SHARMA -> " + found.stream().map(Customer::getFullName).toList());
Customer probe2 = new Customer("a", "example.com", null); CustomerSearchDemo.print("name has a, email has example.com", customers.findAll(Example.of(probe2, matcher), PageRequest.of(0, 3, Sort.by("id")))); }}$ java -jar target/page-lab-0.1.0.jar --demo=qbe DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where lower(c1_0.full_name) like ? escape '\\' order by c1_0.customer_id name has SHARMA -> [Priya Sharma] DEBUG org.hibernate.SQL : select c1_0.customer_id,c1_0.created_at,c1_0.email,c1_0.full_name,c1_0.phone from customers c1_0 where lower(c1_0.full_name) like ? escape '\\' and lower(c1_0.email) like ? escape '\\' order by c1_0.customer_id limit ?,? DEBUG org.hibernate.SQL : select count(c1_0.customer_id) from customers c1_0 where lower(c1_0.full_name) like ? escape '\\' and lower(c1_0.email) like ? escape '\\' name has a, email has example.com -> [Asha Rao, Ravi Kumar, Meena Iyer] total=8
What this code does
- The probe has only
fullName = "SHARMA"; the matcher turns it intolower(full_name) like ?(contains, ignoring case). - The second probe fills name and email, so both become conditions joined with AND; it works with a
Pageabletoo. - There is no way to say "name OR email" or "has an address in Pune" with QBE.
An ExampleMatcher says how text is compared: exact, starts with, contains, ignoring case. JpaRepository already supports QBE through findAll(Example, Pageable), and it needs no Criteria code, so it is quick for simple screens.
Its limits come fast. QBE cannot do OR between fields, ranges (price >= 500), conditions on collections such as "has an address in Pune", or nested logic. When a search needs any of those, use Specifications.
Next step
Check your understanding
11 quick questions