Dynamic filtering with JPA Specifications
Composable WHERE clauses with the Criteria API. HostelSpecifications.filterHostels, ReportSubmissionSpecs.isAccessibleBy, and the alternatives (Querydsl, jOOQ, derived queries).
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
module/hostel/specification/HostelSpecifications.javafilterHostels(search, genderPolicy, isActive), with the same pattern for Room, Landmark and Waitlist specifications, each combined with Pageable.
module/report/application/ReportSubmissionSpecs.javaRM 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) |
Related concepts you must know
- JPA static metamodel.
Hostel_.nameinstead of"name"gives compile-time safety (generated byhibernate-jpamodelgen). LIKE '%x%'can’t use a B-tree index. For substring search at scale usepg_trgmwith 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 callquery.distinct(true)when joining collections.