之前发过用JPA接口动态查询,单独写了个EXT扩展类拼接sql语句,随着我入行时间的增加,我变强了,所以我在这里记录分享一个更为简单的动态分页查询方法。
废话少说,上代码了:
public Page<QualityTaskDto> findQualityTaskByPage(Integer pageNum, Integer pageSize, String tasktype, String jobname, String satellite) {
Sort sort = Sort.by(Sort.Direction.ASC, "creatTime");
Pageable pageable = new PageRequest(pageNum,pageSize,sort);
Specification<DbDmsQualityTaskInfoDTO> specification = (root, query, cb) ->{
List<Predicate> predicates = new LinkedList<>();
if(StringUtils.isNotBlank(tasktype)){
predicates.add(cb.equal(root.get("tasktype"),tasktype));
}
if(StringUtils.isNotBlank(jobname)){
predicates.add(cb.like(root.get("jobname"),"%"+jobname+"%"));
}//模糊查询
if(StringUtils.isNotBlank(satellite)){
predicates.add(cb.equal(root.get("satellite"),satellite));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
Page<DbDmsQualityTaskInfoDTO> all = qualityTaskInfoDAO.findAll(specification,pageable);
List<QualityTaskDto> qualityTaskDtos = qualityTaskDto.db2Dto(all.getContent());
return new PageImpl<>(qualityTaskDtos,pageable,all.getTotalElements());
}
接受参数看具体情况 ,用了拉姆达表达式,这样子然后sql直接可以用jpa内部接口就好了,简单暴力管用,无敌了!