I am trying Spring data JPA in my project. I want to know if there is an out-of-the-box API to query data, by both Sort
and Pageable
. Of course, I
Pageable has an option to specify sort as well. From the java doc
PageRequest(int page, int size, Sort.Direction direction, String... properties)
Creates a new PageRequest with sort parameters applied.
In my case, to use Pageable
and Sorting
at the same time I used like below. In this case I took all elements using pagination and sorting by id
by descending order:
modelRepository.findAll(PageRequest.of(page, 10, Sort.by("id").descending()))
Like above based on your requirements you can sort data with 2 columns as well.
Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.
request:
domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20
That should return a sorted pageable by field provided in the provided order.
There are two ways to achieve this:
final PageRequest page1 = new PageRequest(
0, 20, Direction.ASC, "lastName", "salary"
);
final PageRequest page2 = new PageRequest(
0, 20, new Sort(
new Order(Direction.ASC, "lastName"),
new Order(Direction.DESC, "salary")
)
);
dao.findAll(page1);
As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC
).
in 2020, the accepted answer is kinda out of date since the PageRequest
is deprecated, so you should use code like this :
Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);
public List<Model> getAllData(Pageable pageable){
List<Model> models= new ArrayList<>();
modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
return models;
}