使用 Spring Data JPA 进行分页和排序

3 篇文章 0 订阅

1. 概述

当我们有一个大数据集并且我们想以较小的块将其呈现给用户时,分页通常很有用。

此外,我们经常需要在分页时根据某些标准对数据进行排序。

在本教程中,我们将学习如何使用 Spring Data JPA 轻松地进行分页和排序。

2. 初始设置

首先,假设我们有一个Product实体作为我们的域类:

@Entity 
public class Product {
    
    @Id
    private long id;
    private String name;
    private double price; 

    // constructors, getters and setters 

}

我们的每个Product实例都有一个唯一的标识符:id,它的name和与之相关的price

3. 创建存储库

要访问我们的Product,我们需要一个 ProductRepository

public interface ProductRepository extends PagingAndSortingRepository<Product, Integer> {

    List<Product> findAllByPrice(double price, Pageable pageable);
}

通过让它扩展PagingAndSortingRepository,我们得到 了findAll(Pageable pageable)findAll(Sort sort) 方法来进行分页和排序。

相反,我们可以选择扩展JpaRepository ,因为它也扩展 了 PagingAndSortingRepository

一旦我们扩展了 PagingAndSortingRepository,我们就可以添加我们自己的方法,将 PageableSort 作为参数,就像我们在这里对findAllByPrice所做的那样。

让我们来看看如何 使用我们的新方法对我们的Product进行分页。

4. 分页

一旦我们的存储库从PagingAndSortingRepository扩展,我们只需要:

  1. 创建或获取PageRequest对象,该对象是Pageable接口的实现
  2. PageRequest对象作为参数传递给我们打算使用的存储库方法

我们可以通过传入请求的页码和页面大小来创建一个PageRequest对象。

这里的页数从零开始:

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

Pageable secondPageWithFiveElements = PageRequest.of(1, 5);

在 Spring MVC 中,我们还可以选择使用Spring Data Web Support在我们的控制器中获取Pageable实例。

一旦我们有了PageRequest对象,我们就可以在调用存储库的方法时将其传入:

Page<Product> allProducts = productRepository.findAll(firstPageWithTwoElements);

List<Product> allTenDollarProducts = 
  productRepository.findAllByPrice(10, secondPageWithFiveElements);

findAll(Pageable pageable)方法默认返回一个Page<T> 对象。

但是,我们可以选择从任何返回分页数据的自定义方法返回Page<T> Slice<T>List<T>

Page<T>实例除了拥有Product的列表外,还知道可用页面的总数。**它会触发一个额外的计数查询来实现它。为了避免这种开销成本,我们可以改为返回Slice<T>List<T>

Slice只知道下一个slice 是否可用。

5. 分页和排序

同样,为了对查询结果进行排序,我们可以简单地 将Sort的实例传递给该方法:

Page<Product> allProductsSortedByName = productRepository.findAll(Sort.by("name"));

但是,如果我们想要对数据进行排序和分页怎么办?

我们可以通过将排序细节传递给我们的PageRequest对象本身来做到这一点:

Pageable sortedByName = 
  PageRequest.of(0, 3, Sort.by("name"));

Pageable sortedByPriceDesc = 
  PageRequest.of(0, 3, Sort.by("price").descending());

Pageable sortedByPriceDescNameAsc = 
  PageRequest.of(0, 5, Sort.by("price").descending().and(Sort.by("name")));

根据我们的排序要求,我们可以在创建PageRequest实例时指定排序字段和排序方向。

像往常一样,然后我们可以将此Pageable类型实例传递给存储库的方法。

6. 结论

在本文中,我们学习了如何在 Spring Data JPA 中对查询结果进行分页和排序。

与往常一样,本文中使用的完整代码示例可在 Github 上获得。

使用Spring Data JPA进行分页查询需要遵循以下步骤: 1. 定义Repository接口,继承JpaRepository或其它Spring Data提供的Repository接口。 ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 2. 在Controller中注入Repository,并使用Pageable参数注入分页参数。 ```java @Autowired private UserRepository userRepository; @GetMapping("/users") public Page<User> getUsers(Pageable pageable) { return userRepository.findAll(pageable); } ``` 3. 在前端页面中传递分页参数,例如使用thymeleaf的分页标签: ```html <div class="pagination"> <ul> <li th:class="${users.first} ? disabled"><a th:href="@{${#httpServletRequest.requestURI}(page=0,size=${users.size},sort=${users.sort})}">«</a></li> <li th:class="${users.number == 0} ? disabled"><a th:href="@{${#httpServletRequest.requestURI}(page=${users.number - 1},size=${users.size},sort=${users.sort})}">‹</a></li> <li th:each="i : ${#numbers.sequence(0, users.totalPages - 1)}" th:class="${users.number == i} ? active"><a th:href="@{${#httpServletRequest.requestURI}(page=${i},size=${users.size},sort=${users.sort})}" th:text="${i + 1}"></a></li> <li th:class="${users.number == users.totalPages - 1} ? disabled"><a th:href="@{${#httpServletRequest.requestURI}(page=${users.number + 1},size=${users.size},sort=${users.sort})}">›</a></li> <li th:class="${users.last} ? disabled"><a th:href="@{${#httpServletRequest.requestURI}(page=${users.totalPages - 1},size=${users.size},sort=${users.sort})}">»</a></li> </ul> </div> ``` 以上就是使用Spring Data JPA进行分页查询的基本步骤,可以根据自己的需求进行更加灵活的配置和使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值