其他分享
首页 > 其他分享> > spring boot jpa 复杂查询 动态查询 连接and和or 模糊查询 分页查询

spring boot jpa 复杂查询 动态查询 连接and和or 模糊查询 分页查询

作者:互联网

@Override
public SispPage<AnnouncementEntity> findAnnouncementList(Integer pageNo, Integer pageSize, String t1, String t2, String t3, String t4) {
Sort sort = new Sort(Sort.Direction.DESC, "createTime");
if (pageNo <= 1) {
pageNo = 0;
} else {
pageNo -= 1;
}
PageRequest pageRequest = PageRequest.of(pageNo, pageSize, sort);
Specification<A> specification = new Specification<A>() {
@Override
public Predicate toPredicate(Root<A> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicates = new ArrayList<>();
List<Predicate> predicateOr = new ArrayList<>();
Predicate conditionPre;
predicates.add(criteriaBuilder.equal(root.get("enable").as(String.class), 1));
if (StringUtils.isNotBlank(t1)) {
predicates.add(criteriaBuilder.like(root.get("title").as(String.class), "%" + t1+ "%"));
}

if (StringUtils.isNotBlank(t2)) {
predicates.add(criteriaBuilder.equal(root.get("announcementType").as(String.class), t2));
}
if (StringUtils.isNotBlank(t3)) {
predicates.add(criteriaBuilder.equal(root.get("department").as(String.class), t3));
}
if (StringUtils.isNotBlank(t4)) {
predicateOr.add(criteriaBuilder.like(root.get("noteName").as(String.class), "%" + t4+ "%"));
predicateOr.add(criteriaBuilder.like(root.get("nameZh").as(String.class), "%" + t4+ "%"));
conditionPre = criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])),
criteriaBuilder.or(predicateOr.toArray(new Predicate[predicateOr.size()]))).getRestriction();
} else {
conditionPre = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
}
return conditionPre;
}
};

Page<AnnouncementEntity> announcementPage = announcementDao.findAll(specification, pageRequest);
List<AnnouncementEntity> announcementEntityList = announcementPage.getContent();


return announcementEntityList;
}

标签:String,get,jpa,spring,查询,criteriaBuilder,predicates,new,root
来源: https://www.cnblogs.com/lalalazar/p/12019151.html