7.14_JPA配合 example + 简单 或 复杂排序规则 + 分页

首先是简单或者复杂排序的统一

单个字段的排序(统一前)

	@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);
	}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值