Spring Data Specification的用法,group by,order by及复杂情况和Pageable的注意事项

接口层实现JpaSpecificationExecutor

public interface IPageJpaOpt extends JpaSpecificationExecutor<Page>

JpaSpecificationExecutor接口为我们提供了几个常用方法, 如:

	/**
	 * Returns a {@link Page} of entities matching the given {@link Specification}.
	 *
	 * @param spec can be {@literal null}.
	 * @param pageable must not be {@literal null}.
	 * @return never {@literal null}.
	 */
	Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);

	/**
	 * Returns all entities matching the given {@link Specification} and {@link Sort}.
	 *
	 * @param spec can be {@literal null}.
	 * @param sort must not be {@literal null}.
	 * @return never {@literal null}.
	 */
	List<T> findAll(@Nullable Specification<T> spec, Sort sort);

这里以fandAll为例

                               //这里使用了lamba表达式
		Specification<Page> sp = (root, query, cb) -> {
		    //这里我们可以把fp理解为where的第一层  如 where 1=1
			Predicate fp = cb.conjunction();
			//创建了第一个查询条件 category='4'
			Predicate p1 = cb.equal(root.get("category").as(String.class), "4");
			//这我们将第一层与第一个查询条件合并 where 1=1 and category='4' 
			fp = cb.and(fp, p1);
			//创建第二个查询条件 state='1'
			Predicate p2 = cb.equal(root.get("state").as(String.class), "1");
			//将第一层与第二个查询条件合并 where 1=1 and category='4' and state='1'
			fp = cb.and(fp, p2); 
			//创建了查询条件activityId != null
			Predicate p3 = cb.isNotNull(root.get("activityId"));
			//创建了查询条件rooId != null
			Predicate p4 = cb.isNotNull(root.get("rooId"));
			//这我们希望p3与p4是or连接, 与第一层是and连接
			// where 1=1 and category='4' and state='1' and (activityId != null or rooId != null)
			fp = cb.and(fp, cb.or(p3, p4));
			//这里我们可以从最里层向外读, cb.or(p3, p4)=p3和p4用or连接
			//cb.and(fp, cb.or(p3, p4))=将p3和p4的连接结果与fp用and连接
			return query.where(fp).getRestriction();
			//如果我们想加group by的话  group by category 多个group传List
			return query.where(fp).groupBy(root.get("category")).getRestriction();
			//如果我们想加order的话, 默认asc, order by category asc,多个order传List
			return query.where(fp).groupBy(root.get("category")).orderBy(new OrderImpl(root.get("category"))).getRestriction();
			//order by category desc
			return query.where(fp).groupBy(root.get("category")).orderBy(new OrderImpl(root.get("category")).reverse()).getRestriction();
		};

这里注意如果我们使用了
Page<T> findAll(@Nullable Specification<T> spec, Pageable pageable);
我们通常会使用如下代码
Pageable pageable = new PageRequest(pageNumber, pageSize);
但是这种写法官方已经不推荐了, 建议我们使用如下代码
Pageable pageable = PageRequest.of(pageNumber, pageSize);

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值