Java – Filtering data with Spring boot CrudRepository

java, rest, spring-boot, spring-data, spring-data-jpa

I have a simple REST service which access data with Spring boot CrudRepository.

This repository already implements pagination and sorting capabilities like this:

public interface FlightRepository extends CrudRepository<Flight, Long> {  List<Flight> findAll(Pageable pageable);}

Calling it:

Sort sort = new Sort(direction, ordering);PageRequest page = new PageRequest(xoffset, xbase, sort);return flightRepo.findAll(page);

I would like to add also filtering to this repository (for example return only entities with id > 13 AND id < 27). The CrudRepository does not seem to support this functionality. Is there some way how to achieve this or do I need to use different approach?

Thanks for any tips!

Best Solution

An alternative, which would address your concern in the comments above about having to create query methods for every combination of parameters, is to use the Specification pattern via either the Criteria API or by using QueryDSL.

Both approaches are outlined at the below in response to the concern that:

the number of query methods might grow for larger applications because of - and that’s the second point - the queries define a fixed set of criterias. To avoid these two drawbacks, wouldn’t it be cool if you could come up with a set of atomic predicates that you could combine dynamically to build your query?

I find QueryDSL a bit easier to work with. You need only define one interface method which you can then pass any combination of parameters to as a predicate.


public interface UserRepository extends PagingAndSortingRepository<User, Long>, QueryDslPredicateExecutor<User> {    public List<User> findAll(Predicate predicate);}

and to query:


where QUser is a QueryDSL auto-generated class.


From the Gosling release of the Spring Data module there is now support for automatic predicate generation from HTTP parameters in a web application.