首先是简单或者复杂排序的统一
单个字段的排序(统一前)
@Test
public void singleSort_with_noPage1(){
List<Mysql_Entity_Test> result = testRepository.findAll(Sort.by(Sort.Direction.DESC,"name"));
result.stream().forEach(new Consumer<Mysql_Entity_Test>() {
@Override
public void accept(Mysql_Entity_Test mysql_entity_test) {
System.out.println(mysql_entity_test);
}
});
}
单个字段的排序(统一后)
@Test
public void singleSort_with_noPage2(){
List<Sort.Order>orderList=new ArrayList<>();
orderList.add(Sort.Order.desc("name"));
List<Mysql_Entity_Test> all = testRepository.findAll(Sort.by(orderList));
all.stream().forEach(a-> System.out.println(a));
}
多个字段的排序
@Test
public void multiSort_with_noPage(){
List<Sort.Order>orderList=new ArrayList<>();
orderList.add(Sort.Order.asc("name"));
orderList.add(Sort.Order.desc("age"));
List<Mysql_Entity_Test> all = testRepository.findAll(Sort.by(orderList));
all.stream().forEach(mysql_entity_test -> System.out.println(mysql_entity_test));
}
统一成将排序规则放入数组的形式。虽然单一排序规则有着更加简单的写法(其实也简单不了多少),但是统一之后,更好记。
然后是 example + 排序规则 的使用
@Test
public void singleOrMultiSort_with_example(){
/*排序规则*/
List<Sort.Order>orderList=new ArrayList<>();
orderList.add(Sort.Order.desc("age"));
/*匹配规则——————注意,这里不是使用Example去创建对象,而是使用自己写的实体类去创建对象*/
Mysql_Entity_Test example=new Mysql_Entity_Test();
example.setName("lisi");
/*查找*/
List<Mysql_Entity_Test> all = testRepository.
findAll(Example.of(example), Sort.by(orderList));
all.stream().forEach(a-> System.out.println(a));
}
最后是 example + 排序规则 + 分页
这里排序规则要写在分页参数里面,不再是单独的一个参数传给findall方法了
PageRequest.of(int 当前页,从0开始算 , int 一页有几条数据),
例如
PageRequest.of(0,20);
@Test
public void singleOrMultiSort_with_page_with_example(){
/*匹配条件*/
Mysql_Entity_Test example=new Mysql_Entity_Test();
example.setName("lisi");
/*分页 和 排序规则————————注意:这里的排序规则成为了分页对象的一个参数*/
List<Sort.Order>orderList=new ArrayList<>();
orderList.add(Sort.Order.desc("age"));
Pageable pageable=PageRequest.of(0,2,Sort.by(orderList));
/*查找————使用example和分页参数,而排序规则又在分页里面*/
testRepository.findAll(Example.of(example),pageable);
}