Spring Data JPA條件查詢
阿新 • • 發佈:2020-07-24
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); }