Video in progress
In Spring Data JPA, how do you write a search with many optional filters using the Specification pattern, and what are its limits?
Specification turns each filter condition into a separate, reusable object and combines them with and/or. In Spring Data, JpaSpecificationExecutor and Specification<T> provide this on top of the Criteria API; you don't need a separate repository method for every combination.
📖 Answer
A course search: category, price range, language, rating, all optional. The findByCategoryAndPriceBetweenAndLang... route leads to 16 methods.
public final class CourseSpecs {
public static Specification<Course> inCategory(Long id) {
return (root, q, cb) -> id == null ? null : cb.equal(root.get("category").get("id"), id);
}
public static Specification<Course> priceBetween(BigDecimal min, BigDecimal max) {
return (root, q, cb) -> {
if (min == null && max == null) return null;
if (min == null) return cb.le(root.get("price"), max);
if (max == null) return cb.ge(root.get("price"), min);
return cb.between(root.get("price"), min, max);
};
}
public static Specification<Course> published() {
return (root, q, cb) -> cb.isTrue(root.get("published"));
}
}
Page<Course> page = repo.findAll(
Specification.where(published())
.and(inCategory(f.categoryId()))
.and(priceBetween(f.min(), f.max())),
pageable);
A condition that returns null is ignored, and that makes optional filters easy.
Limits and traps:
root.get("price")is a string. If the field name changes, the error only shows up at runtime. If you generate the Hibernate JPA Metamodel (Course_.price), it becomes type-safe.- When specs that
joinare combined, the same table can get joined twice, producing duplicate rows; you then needquery.distinct(true), which is expensive with pagination. - For a
Page, Spring also sends a separatecountquery, which can be slow too with a complex spec. - It's awkward to use together with projections and
fetch join.
For very complex, report-style searches I usually pick Querydsl, jOOQ or plain native SQL. Specification is the most convenient middle ground for 5–10 simple filters.
Sign up to mark studied questions and save your progress.