spring JPA ---分页 排序 功能

520 阅读1分钟

这是我参与11月更文挑战的第14天,活动详情查看:[2021最后一次更文挑战]

用到:Spring PagingAndSortingRepository

分页

//要求提供第一页(0)
Pageable pageable = PageRequest.of(0, 10);
Page<Employee> page = employeeRepository.findAll(pageable);

//要求提供第*-1页
PageRequest.of(1, 10);
PageRequest.of(2, 10);
PageRequest.of(3, 10);

排序

employeeRepository.findAll(Sort.by("fistName"));
employeeRepository.findAll(Sort.by("fistName").ascending().and(Sort.by("lastName").descending());
//显然,第一个按“firstName”排序,另一个按“firstName”升序和“lastName”降序排序。

分页和排序

Pageable pageable = PageRequest.of(0, 20, Sort.by("firstName"));
Pageable pageable = PageRequest.of(0, 20, Sort.by("fistName").ascending().and(Sort.by("lastName").descending());

页 page

Page 是Slice的一个子接口, 并有几个额外的方法。它知道表中的总页数以及记录总数。以下是一些重要的方法。

static <T> Page<T> empty; //创建一个空页
long getTotalElements(); // 每一页总共几个元素
int totalPages() // 总共几页