多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
将查询方法最后一个参数传入`Pageable`或`Sort`来完成分页或排序。 ```java package org.springframework.data.domain; //Pageable 可以调用 PageRequest.of 方法构造 public class PageRequest extends AbstractPageRequest { //只分页不排序 //page 从 0 开始 public static PageRequest of(int page, int size) //既分页又排序。排序可以升序也可以降序 public static PageRequest of(int page, int size, Sort sort) //既分页又排序。排序只能是降序或升序 public static PageRequest of(int page, int size, Direction direction, String... properties) } ``` >[info]page 从 0 开始。 ```java package org.springframework.data.domain; //Sort 调用 Sort.by 方法构造 public class Sort implements Streamable<Sort.Order>, Serializable { //默认并且只能升序排序 public static Sort by(String... properties) //同一条语句既可以升序排序,也可以降序排序 public static Sort by(List<Sort.Order> orders) public static Sort by(Sort.Order... orders) //同一条语句只能按照升序,或降序排序 public static Sort by(Sort.Direction direction, String... properties) } ``` <br/> **示例1:** ```java List<Person> findAllByGender(String gender, Sort sort); Page<Person> findAllByGender(String gender, Pageable pageable); @Query("from Person p where p.gender = ?1") Page<Person> findAllByGenderHsql(String gender, Pageable pageable); /** * 原生SQL语句分页查询,必须要结合 countQuery 查询出总数 */ @Query(value = "select * from tb_person where gender = ?1", countQuery = "select count(*) from tb_person where gender = ?1", nativeQuery = true) Page<Person> findAllByGenderSql(String gender, Pageable pageable); ``` ```java List<Person> personList = personRepository.findAllByGender("男", Sort.by("age")); Pageable pageable = PageRequest.of(1, 5, Sort.Direction.DESC, "age"); Page<Person> personPage = personRepository.findAllByGender("男", pageable); ``` <br/> **2. 示例2:** ```java Specification<Person> spec = (root, query, cBuilder) -> { return cBuilder.equal(root.get("gender"), "男"); }; List<Person> personList = personRepository.findAll(spec, Sort.by(Sort.Direction.DESC, "age")); Pageable pageable = PageRequest.of(0, 5, Sort.by(Sort.Direction.DESC, "age")); Page<Person> personPage = personRepository.findAll(spec, pageable); ```