BBackend CourseLeroy Labs
0/0
Search the course

Dynamic filtering with JPA Specifications

Composable WHERE clauses with the Criteria API. HostelSpecifications.filterHostels, ReportSubmissionSpecs.isAccessibleBy, and the alternatives (Querydsl, jOOQ, derived queries).

● intermediateHostel-Web-AppReport-Manager-2

The concept

Search screens have optional filters, and each combination is a different query. Writing findByNameAndGenderAndActive, findByName, findByGenderAndActive… causes a combinatorial explosion. A Specification is one reusable predicate, and you combine them with and/or:

public interface HostelRepository extends JpaRepository<Hostel, UUID>,
                                          JpaSpecificationExecutor<Hostel> {}

public final class HostelSpecifications {
    public static Specification<Hostel> nameContains(String q) {
        return (root, query, cb) -> q == null ? null
            : cb.like(cb.lower(root.get("name")), "%" + q.toLowerCase() + "%");
    }
    public static Specification<Hostel> genderPolicy(GenderPolicy g) {
        return (root, query, cb) -> g == null ? null : cb.equal(root.get("genderPolicy"), g);
    }
    public static Specification<Hostel> active(Boolean a) {
        return (root, query, cb) -> a == null ? null : cb.equal(root.get("isActive"), a);
    }
    public static Specification<Hostel> filterHostels(String q, GenderPolicy g, Boolean a) {
        return Specification.allOf(nameContains(q), genderPolicy(g), active(a)); // nulls are skipped
    }
}

// service
Page<Hostel> page = hostelRepository.findAll(HostelSpecifications.filterHostels(q, g, a), pageable);

A predicate that returns null is ignored, so missing filters simply drop out of the query. The values are bound as parameters, which means no SQL injection.

In your projects

Hostel-Web-Appmodule/hostel/specification/HostelSpecifications.java

filterHostels(search, genderPolicy, isActive), with the same pattern for Room, Landmark and Waitlist specifications, each combined with Pageable.

Report-Manager-2module/report/application/ReportSubmissionSpecs.java

RM uses Specifications for authorization-aware filtering:

Specification<ReportSubmission> spec = ReportSubmissionSpecs
    .isAccessibleBy(approvableUnitIds, callerUnitId)  // row-level security in code
    .and(ReportSubmissionSpecs.withFilters(filters))
    .and(ReportSubmissionSpecs.isPendingApproval());

Making access a reusable predicate means every list query applies it, so a user can’t see another unit’s reports just because a developer forgot a WHERE.

Alternatives

Tool Pros Cons
Specifications (yours) Built in, composable Verbose; string attribute names unless you use the JPA metamodel
Derived queries findByXAndY Zero code for fixed queries Explodes with optional filters
@Query with (:x IS NULL OR col = :x) One query Can defeat index use and query-plan caching
Querydsl Type-safe fluent API Code generation; slower releases
jOOQ Type-safe SQL, full Postgres power Not JPA; a commercial licence for some databases
Criteria API directly Full control Very verbose
Search engine (Elasticsearch) Full-text, facets, relevance Another system to sync (bonus module)
  • JPA static metamodel. Hostel_.name instead of "name" gives compile-time safety (generated by hibernate-jpamodelgen).
  • LIKE '%x%' can’t use a B-tree index. For substring search at scale use pg_trgm with a GIN index, or full-text search (tsvector).
  • Row-level security. RM enforces it in code with specs, SperoTek with Hibernate @TenantId. Postgres also has native RLS policies (see the multi-tenancy lesson).
  • Joins in specs. root.join("hostel") can duplicate rows, so call query.distinct(true) when joining collections.

Check yourself

1. What happens when a Specification returns null?
2. Why make isAccessibleBy a spec in RM?