java / intermediate
Snippet
Dynamische Filterung mit JPA-Spezifikationen
JPA-Spezifikationen ermöglichen es Ihnen, komplexe, dynamische Abfragen programmatisch über die Criteria-API zu erstellen. Dies entkoppelt die Suchlogik vom Repository und macht sie hochgradig wiederverwendbar.
snippet.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 ServiceList<Product> results = repository.findAll(Specification.where(hasCategory("Electronics")).and(priceLessThan(500.0)));
spring
Erklärung
1
Specification<Product>
Definiert ein wiederverwendbares Prädikat für die Entität Product.
2
(root, query, cb) -> ...
Lambda-Ausdruck, der die toPredicate-Methode unter Verwendung von Root, CriteriaQuery und CriteriaBuilder implementiert.
3
Specification.where(...).and(...)
Fluent-API zum Kombinieren mehrerer Spezifikationen zu einer einzigen dynamischen Abfrage.