Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query data out of the box using Spring data JPA by both Sort and Pageable?

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.

like image 626
Tom Avatar asked May 10 '12 03:05

Tom


People also ask

Is it possible to define a sort type in @query annotation using Spring JPA?

Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.


1 Answers

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

like image 178
Tomasz Nurkiewicz Avatar answered Sep 18 '22 13:09

Tomasz Nurkiewicz