如何通过Sort和Pageable使用Spring数据JPA查询开箱即用的数据? [英] How to query data out of the box using Spring data JPA by both Sort and Pageable?
问题描述
我正在我的项目中尝试 Spring data JPA 。我想通过排序
和 Pageable
。当然,我知道我自己可以写这个方法,我只是想知道是否有一个开箱即用的方法。我的DAO扩展 JpaRepository
,我发现我可以调用以下方法:
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);
但是没有像这样的方法findAll(Sort sort,Pageable pageable)
,所以我很好奇。
But there is no such method as findAll(Sort sort, Pageable pageable)
, so I am curious.
推荐答案
有两种方法可以达到这个目的:
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);
正如您所看到的,第二种形式更灵活,因为它允许为每个属性定义不同的方向( lastName ASC,薪水DESC
)。
As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC
).
这篇关于如何通过Sort和Pageable使用Spring数据JPA查询开箱即用的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!