Video in progress

Strong Middle 🌱 Spring

How do you build a dynamic query from user-selected filters in Spring Data?

With Specification (on top of the JPA Criteria API), Querydsl or Query by Example. Each filter is a separate condition added depending on the incoming parameter, so you don't end up with a pile of findByAAndBAndC methods.

📖 Answer

Say a product search: category, price range, name, all optional.

public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> { }

class ProductSpecs {
    static Specification<Product> category(String c) {
        return (root, q, cb) -> c == null ? null : cb.equal(root.get("category"), c);
    }
    static Specification<Product> priceBetween(BigDecimal min, BigDecimal max) {
        return (root, q, cb) -> {
            if (min == null && max == null) return null;
            if (max == null) return cb.ge(root.get("price"), min);
            if (min == null) return cb.le(root.get("price"), max);
            return cb.between(root.get("price"), min, max);
        };
    }
    static Specification<Product> nameLike(String s) {
        return (root, q, cb) -> s == null ? null
            : cb.like(cb.lower(root.get("name")), "%" + s.toLowerCase() + "%");
    }
}

Page<Product> page = repo.findAll(
    Specification.where(category(f.category()))
        .and(priceBetween(f.min(), f.max()))
        .and(nameLike(f.q())),
    pageable);

A condition that returns null is simply skipped.

like '%...%' doesn't use a regular B-tree index, so on a big table you need pg_trgm or full-text search. Since field names are strings ("price"), they break easily in a refactoring; the JPA metamodel (Product_.price) or Querydsl checks the types. Also don't allow sorting by any column; validate against an allowlist.