Dynamic Filtering Spring JpaRepository
To filter data dynamicaly on JPA repository Example type will be helpfull.
we create default JpaRepository
public interface ProductRepository extends JpaRepository<ProductEntity,Long> {
}
magic is starting here when calling jpa repository default method findAll(Example<S> example). This method filters data by filled values of entity class(here productEntity)
productRepository.findAll(Example.of(productEntity));
example repository for call filter by name equals “phone” products
ProductEntity productEntity = new ProductEntity();
productEntity.setName("phone")
productRepository.findAll(Example.of(productEntity));
example repository for call filter by type equals “clothes” products
ProductEntity productEntity = new ProductEntity();
productEntity.setType("clothes")
productRepository.findAll(Example.of(productEntity));
example repository for call all products(no filter)
ProductEntity productEntity = new ProductEntity();
productRepository.findAll(Example.of(productEntity));
Controller for dynamic input from rest request
this controller can handle data from request parameters
Examples: byfilter?name=phone, byfilter?type=clothes
@RestController
@RequiredArgsConstructor
public class ProductController {
private final ProductService productService;
@GetMapping("/productlist/byfilter")
public List<ProductEntity> getProductListByFilter(ProductEntity productEntity) {
return productService.getProductListByFilter(productEntity);
}
}
Service for dynamic input from rest request
@Service
@RequiredArgsConstructor
public class ProductServiceImpl implements ProductService{
private final ProductRepository productRepository;
@Override
public List<ProductEntity> getProductListByFilter(ProductEntity productEntity) {
return productRepository.findAll(Example.of(productEntity));
}
}
Example project to try is here
example requests for project. Example data auto initialize on start by InitTestData class
GET: http://localhost:8080/productlist/byfilter
GET: http://localhost:8080/productlist/byfilter?name=phone
GET: http://localhost:8080/productlist/byfilter?type=clothes