Dynamic Filtering
Simple QUERY METHODS (jaise findByCategory), FIXED, PREDICTABLE FILTERS ke liye, ACHHE HAIN. LEKIN, JAB, USER, RUNTIME PAR, MULTIPLE, OPTIONAL FILTERS (jaise "category AND price > X AND name CONTAINS Y", JAHA, HAR FILTER, OPTIONAL hai) COMBINE karna CHAHTA hai, Spring Data JPA Specifications, USEFUL hoती hain.
Specification<T> INTERFACE, EK "PREDICATE BUILDER" hai — RUNTIME PAR, DYNAMICALLY, WHERE CLAUSE, CONSTRUCT ki ja sakti hai, HAR FILTER CRITERIA ke, PRESENT/ABSENT HONE ke, HISAAB SE.
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> priceGreaterThan(BigDecimal min) {
return (root, query, cb) -> min == null ? null :
cb.greaterThan(root.get("price"), min);
}
}
// Controller mein, DYNAMICALLY, COMBINE karna:
@GetMapping
public List<ProductDto> search(
@RequestParam(required = false) String category,
@RequestParam(required = false) BigDecimal minPrice) {
Specification<Product> spec = Specification
.where(ProductSpecifications.hasCategory(category))
.and(ProductSpecifications.priceGreaterThan(minPrice));
return productRepository.findAll(spec).stream().map(this::toDto).toList();
}- Specifications = runtime par, dynamically, WHERE clauses build karne ka way
- Optional filters (jaise category OPTIONAL), Specifications se, EASILY handle hote hain
- JpaSpecificationExecutor<T>, repository mein, extend karna padta hai
QueryDSL, EK, DUSRA, POPULAR, LIBRARY hai, DYNAMIC, TYPE-SAFE, QUERIES BANANE ke liye — Specifications SE, ZYAADA, FLUENT, SYNTAX DETA hai, LEKIN, EXTRA, CODE-GENERATION, STEP (Q-CLASSES) MANGТА hai.
Specification.where(spec1).and(spec2).or(spec3) — COMPLEX, BOOLEAN, LOGIC, EASILY, CHAIN ki ja sakti hai — RUNTIME PAR, DECIDE karo, KAUN SE, SPECS, COMBINE karne hain, USER ke, ACTUAL, INPUT ke, HISAAB SE.
Specification<Product> spec = Specification.where(null);
if (category != null) spec = spec.and(hasCategory(category));
if (minPrice != null) spec = spec.and(priceGreaterThan(minPrice));