繁体   English   中英

如何通过排序和分页使用 Spring 数据 JPA 开箱即用地查询数据?

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

我正在我的项目中尝试Spring 数据 JPA 我想知道是否有开箱即用的 API 通过SortPageable查询数据。 当然,我知道我可以自己编写那个方法,我只是想知道是否有一个开箱即用的方法。 我的 DAO 扩展JpaRepository ,我发现可以调用以下方法:

findAll();
findAll(Pageable pageable);
findAll(Sort sort);

但是没有findAll(Sort sort, Pageable pageable)这样的方法,所以我很好奇。

有两种方法可以实现这一点:

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

Pageable 也有一个选项来指定排序。 来自java 文档

PageRequest(int page, int size, Sort.Direction direction, String... properties) 

创建一个应用了排序参数的新 PageRequest。

在 2020 年,接受的答案有点过时,因为PageRequest已被弃用,因此您应该使用如下代码:

Pageable page = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by("id").descending());
return repository.findAll(page);

Spring Pageable包含一个 Sort 。 因此,如果您的请求具有值,它将返回一个排序的可分页。

请求: domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20

这应该返回按提供的顺序提供的按字段排序的可分页。

在我的情况下,要同时使用PageableSorting我使用如下。 在这种情况下,我使用分页和按id按降序排序的所有元素:

modelRepository.findAll(PageRequest.of(page, 10, Sort.by("id").descending()))

像上面一样,根据您的要求,您也可以使用 2 列对数据进行排序。

可以在请求的 URL 中提供排序参数和排序方向。 Spring Pageable automatically parses the URL parameters & creates Pageable object that is obtained by your rest controller. 我相信这是最好的解决方案之一,因为它有助于避免手动 PageRequest/Pageable 对象实例化(注意排序方向之前的逗号字符):

domain.com/endpoint?sort=[FIELD],[asc|desc]&page=3&size=100

PS Spring 文档中描述的排序方向用法的其他示例不适用于我(可能已过时)。

 public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       return models;
   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM