java / intermediate
Snippet
Dynamic Filtering with JPA Specifications
JPA Specifications allow you to build dynamic and reusable queries using the Criteria API. This is much more flexible than writing multiple repository methods for every filter combination.
snippet.java
1
2
3
4
public static Specification<User> hasName(String name) {return (root, query, cb) -> cb.equal(root.get("name"), name);}// Usage: repository.findAll(Specification.where(hasName("John")));
spring
Breakdown
1
(root, query, cb) -> cb.equal(...)
Uses a lambda to define the database predicate (WHERE clause).