如何通过 Sort 和 Pageable 使用 Spring 数据 JPA 查询开箱即用的数据? [英] How to query data out of the box using Spring data JPA by both Sort and Pageable?

查看:14
本文介绍了如何通过 Sort 和 Pageable 使用 Spring 数据 JPA 查询开箱即用的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的项目中尝试 Spring 数据 JPA.我想知道是否有开箱即用的 API 来通过 SortPageable 查询数据.当然,我知道我可以自己编写该方法,我只是想知道是否有开箱即用的方法.我的 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.

推荐答案

有两种方法可以实现:

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,salary 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆