spring data JpaSpecificationExecutor接口分页带多种条件查询

时间:2022-03-31 20:33:09

DAO层继承JpaSpecificationExecutor接口

@Override
public Page<AbnormalEntity> fetchAbnormals(QueryCondition query,Integer page,Integer rows) {

//解析出paramrule对象 取出field,op,value对应的值
List<ParamRules> paramlist = Lists.newArrayList(query.getRules());

final Paraminfo param = new Paraminfo();
for(ParamRules rules:paramlist){
if(rules.getField().equals("companyAreaCode")){
param.setCompanyAreaCode(rules.getValue());
}
if(rules.getField().equals("abntypecode")){
param.setAbntypecode(rules.getValue());
}
if(rules.getField().equals("abntarget")){
param.setAbntarget(rules.getValue());
}
if(rules.getField().equals("state")){
param.setState(rules.getValue());
}
if(rules.getField().equals("abncode")){
param.setAbncode(rules.getValue());
}
if(rules.getField().equals("compname")){
param.setCompname(rules.getValue());
}
if(rules.getField().equals("busbrandno")){
param.setBusbrandno(rules.getValue());
}
if(rules.getField().equals("occurtime_start")){
param.setStartdate(rules.getValue());
}
if(rules.getField().equals("occurtime_end")){
param.setEnddate(rules.getValue());
}
}

Pageable pageable=new PageRequest(page-1, rows,Sort.Direction.ASC,"abncode");
Specification<AbnormalEntity> spec = new Specification<AbnormalEntity>() {
@Override
public Predicate toPredicate(Root<AbnormalEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<>(); 

if(!StringUtils.isEmpty(param.getCompanyAreaCode())){
predicates.add(cb.like(root.get("areacode").as(String.class), "%"+param.getCompanyAreaCode()+"%"));//行政区划编号
}
if(!StringUtils.isEmpty(param.getAbntypecode())){
predicates.add(cb.equal(root.get("abntypecode").as(String.class), param.getAbntypecode()));//异常类型编号
}
if(!StringUtils.isEmpty(param.getAbntarget())){
predicates.add(cb.equal(root.get("abntarget").as(String.class), param.getAbntarget()));//异常对象
}
if(!StringUtils.isEmpty(param.getState())){
predicates.add(cb.equal(root.get("state").as(String.class), param.getState()));//处理状态
}
if(!StringUtils.isEmpty(param.getAbncode())){
predicates.add(cb.equal(root.get("abncode").as(String.class), param.getAbncode()));//异常编号
}
if(!StringUtils.isEmpty(param.getCompname())){
predicates.add(cb.like(root.get("compname").as(String.class), "%"+param.getCompname()+"%"));//业户名称
}
if(!StringUtils.isEmpty(param.getBusbrandno())){
predicates.add(cb.like(root.get("busbrandno").as(String.class), "%"+param.getBusbrandno()+"%"));//车牌号
}
if(!StringUtils.isEmpty(param.getStartdate())){
predicates.add(cb.greaterThanOrEqualTo(root.<Date>get("occurtime"), param.getStartdate()));//开始时间  
}
if(!StringUtils.isEmpty(param.getEnddate())){
predicates.add(cb.lessThanOrEqualTo(root.<Date>get("occurtime"), param.getEnddate()));//结束时间 
}


               // and到一起的话所有条件就是且关系,or就是或关系  
               return cb.and(predicates.toArray(new Predicate[predicates.size()]));  
}
        };
return abnormalDao.findAll(spec,pageable);
}