前言
之前使用jpa的时候一直感慨它的一些原来就有的方法很好用,一边不是很习惯这种不是xml写sql的方式,尤其在用习惯了mybatis之后,在使用jpa写动态查询的时候真的一头雾水,直到发现了**Specification** 这个神奇的东西,使用下来觉得他和mybatis plus的条件构造器很像,而且可以实现动态查询,特意记录一下
代码
JPA
List<Apply> findAll(Specification<Apply> specification);
service
1 public List<Apply> getAllDynamatic(Apply apply) { 2 Specification<Apply> queryCondition = new Specification<Apply>() { 3 @Override 4 public Predicate toPredicate(Root<Apply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { 5 List<Predicate> predicateList = new ArrayList<>(); 6 // 根据传递的对象来进行条件的构造 7 if (apply.getId() != null) { 8 predicateList.add(criteriaBuilder.equal(root.get("id"), apply.getId())); 9 } 10 if (apply.getState() != null) { 11 predicateList.add(criteriaBuilder.equal(root.get("state"), apply.getState())); 12 } 13 if (apply.getAwardtype() != null) { 14 predicateList.add(criteriaBuilder.equal(root.get("awardtype"), apply.getAwardtype())); 15 } 16 if (apply.getStudentid() != null) { 17 predicateList.add(criteriaBuilder.equal(root.get("studentid"), apply.getStudentid())); 18 } 19 if (apply.getInfo() != null) { 20 predicateList.add(criteriaBuilder.equal(root.get("info"), apply.getInfo())); 21 } 22 if (apply.getName() != null) { 23 predicateList.add(criteriaBuilder.equal(root.get("name"), apply.getName())); 24 } 25 if (apply.getType() != null) { 26 predicateList.add(criteriaBuilder.equal(root.get("type"), apply.getType())); 27 } 28 if (apply.getTeacherid() != null) { 29 predicateList.add(criteriaBuilder.equal(root.get("teacherid"), apply.getTeacherid())); 30 } 31 if (apply.getTeacherstate() != null) { 32 predicateList.add(criteriaBuilder.equal(root.get("teacherstate"), apply.getTeacherstate())); 33 } 34 if (apply.getProcess() != null) { 35 predicateList.add(criteriaBuilder.equal(root.get("process"), apply.getProcess())); 36 } 37 if (apply.getProcess2() != null) { 38 predicateList.add(criteriaBuilder.equal(root.get("process2"), apply.getProcess2())); 39 } 40 41 return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()])); 42 } 43 }; 44 return applyRepos.findAll(queryCondition); 45 }
这样就实现了jpa的动态查询