Spring Data JPA条件查询
背景:
最近正在将项目的持久层框架的Spring Data JPA更换成为mybatis,所以留个念想。
代码
@Override
public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
return blogMapper.findAll(new Specification<Blog>() {
@Override
public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
List<Predicate> predicates=new ArrayList<>();
//名称的模糊查询
if (!"".equals(blog.getTitle()) && blog.getTitle()!=null){
predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
}
//类型的查询
if (blog.getTypeId() != null) {
predicates.add(cb.equal(root.<Type>get("type").get("id"),blog.getTypeId()));
}
//是否推荐的查询
if (blog.isRecommend()) {
predicates.add(cb.<Boolean>equal(root.get("recommend"),blog.isRecommend()));
}
cq.where(predicates.toArray(new Predicate[predicates.size()]));
return null;
}
},pageable);
}