Mehmet Ergülcü

Dynamic Filtering Spring JpaRepository

· 1 min

spring-bootdynamic-filters

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

GitHub - ergulcu/exampledynamicquery

Postman: GET localhost:8080/productlist/byfilter with the JSON body {"type": "clothes"} returns 200 OK

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

© 2026 Mehmet Ergülcü SvelteKit · Tailwind · <1 KB JS