0 day streak
java / intermediate
Snippet

Dynamic Filtering with JPA Specifications

JPA Specifications allow you to build complex, dynamic queries programmatically using the Criteria API. This decouples the search logic from the repository and makes it highly reusable.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
public class ProductSpecifications {
public static Specification<Product> hasCategory(String category) {
return (root, query, cb) -> category == null ? null : cb.equal(root.get("category"), category);
}
public static Specification<Product> priceLessThan(Double price) {
return (root, query, cb) -> price == null ? null : cb.lessThan(root.get("price"), price);
}
}
// Usage in Service
List<Product> results = repository.findAll(Specification.where(hasCategory("Electronics")).and(priceLessThan(500.0)));
spring
Breakdown
1
Specification<Product>
Defines a reusable predicate for the Product entity.
2
(root, query, cb) -> ...
Lambda expression implementing the toPredicate method using Root, CriteriaQuery, and CriteriaBuilder.
3
Specification.where(...).and(...)
Fluent API to combine multiple specifications into a single dynamic query.