How to query data out of the box using Spring data JPA by both Sort and Pageable?
JavaSpringJpaSpring Data-JpaJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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
).
Solution 2 - Java
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.
Solution 3 - Java
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);
Solution 4 - Java
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.
Solution 5 - Java
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.
Solution 6 - Java
public List<Model> getAllData(Pageable pageable){
List<Model> models= new ArrayList<>();
modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
return models;
}