spring date jpa 实现动态查询

话不多说,直入正题,之前在百度上想找spring date jpa动态查询是怎么实现的,一直找不到,现在写一下我理解的,如有过错请大神指导。

首先在service层写一个内部类,继承 Specification<T> 接口,定义类型为实体类的属性,写有参构造给属性赋值,重写toPredicate方法。

代码如下:

//内部类实现Specification<T>接口

class ComResourceSpecification implements Specification<ComResource> {

//实体类的私有属性
private ComResource comResource;


public ComResourceSpecification(ComResource comResource) {
this.comResource = comResource;
}


// 查询条件拼接
public Predicate toPredicate(Root<ComResource> root, CriteriaQuery<?> query,
CriteriaBuilder cb) {
if (comResource == null) {
return null;
}
List<Predicate> list = new ArrayList<Predicate>();
// 关键字查询
if (StringUtils.isNotEmpty(comResource.getKeyWord())) {
list.add(cb.or(cb.like(root.get("comResName").as(String.class), "%" + comResource.getKeyWord() + "%"),
cb.like(root.get("address").as(String.class), "%" + comResource.getKeyWord() + "%"),
cb.like(root.get("contactPer").as(String.class), "%" + comResource.getKeyWord() + "%")
));
}


if (StringUtils.isNotEmpty(comResource.getOrgCode())) {
list.add(cb.equal(root.get("orgCode").as(String.class), comResource.getOrgCode()));
}

//更新时间
if(comResource.getStartTime() != null && comResource.getEndTime()!= null){
list.add(cb.between(root.get("updateTime").as(Date.class), comResource.getStartTime(), comResource.getEndTime()));
}else if(comResource.getStartTime() != null && comResource.getEndTime()== null){
list.add(cb.greaterThanOrEqualTo(root.get("updateTime").as(Date.class),comResource.getStartTime()));
}else if(comResource.getStartTime() == null && comResource.getEndTime() != null){
list.add(cb.lessThanOrEqualTo(root.get("updateTime").as(Date.class),comResource.getEndTime()));
}

Predicate[] p = new Predicate[list.size()];
query.where(cb.and(list.toArray(p)));
query.orderBy(cb.desc(root.get("updateTime").as(Date.class)));
return query.getRestriction();
}
}


实现多条件排序:
list<Order> orderList = new ArrayList<Order>();
orderList.add(cb.asc(root.get("updateTime").as(Date.class)));
query.orderBy(orderList);
将要排序的条件放到一个list集合中


需要注意的是,条件都放在list集合里,集合的条件都是以and拼接的,如需用 or 拼接将条件都添加在集合的一个元素中,祥见“关键字查询”那

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值