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 know I can write that method myself, I just want to know if there is an out-of-the-box one. My DAO extends JpaRepository
, and I found there are the following methods I can invoke:
findAll();
findAll(Pageable pageable);
findAll(Sort sort);
But there is no such method as findAll(Sort sort, Pageable pageable)
, so I am curious.
This question is related to
java
spring
jpa
spring-data-jpa
public List<Model> getAllData(Pageable pageable){
List<Model> models= new ArrayList<>();
modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
return models;
}
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);
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.
Source: Stackoverflow.com