BlogNote

A Blog to Share Information

Dynamic Filtering Spring JpaRepository

To filter data dynamically on JPA repository, Example type will be helpful.

We create default JpaRepository:

public interface ProductRepository extends JpaRepository<ProductEntity,Long> {
}

Magic is starting here when calling JPA repository default method findAll(Example&lt;S&gt; 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.

@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:

GitHub - ergulcu/exampledynamicquery

Zoom image will be displayed

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