多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
```java @SpringBootTest public class StudentRepositoryTest { @Autowired private StudentRepository studentRepository; /** * select * from student where name like '张%' and sex='男' */ @Test public void example1() { //构建查询条件 Specification<Student> stuSpec = (root, query, cb) -> { Predicate likeName = cb.like(root.get("name").as(String.class), "张%"); Predicate sexEqual = cb.equal(root.get("sex").as(String.class), "男"); Predicate and = cb.and(likeName, sexEqual); return and; }; List<Student> studentList = studentRepository.findAll(stuSpec); //如果没有数据,则返回空的List,不会返回null System.out.println(studentList); //[Student(id=1, name=张三, age=25, sex=男, total=175), ...] } /** * select distinct * from student where sex='男' */ @Test public void example2() { Specification<Student> stuSpec = (root, query, cb) -> { CriteriaQuery cq = query.distinct(true); Predicate sex = cb.equal(root.get("sex").as(String.class), "男"); return cq.where(sex).getRestriction(); }; List<Student> studentList = studentRepository.findAll(stuSpec); System.out.println(studentList); //[Student(id=1, name=张三, age=25, sex=男, total=175), ... } /** * select * from student where id=? and name=? and (sex=? or total >= ?) */ @Test public void example03() { Student student = Student.builder().id(2).name("李四").age(24).sex("男").total(179).build(); Specification<Student> stuSpec = (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(1); if (student.getId() != null) { Predicate predicate = cb.equal(root.get("id").as(Integer.class), student.getId()); predicates.add(predicate); } if (student.getAge() != null) { Predicate predicate = cb.equal(root.get("age").as(Integer.class), student.getAge()); predicates.add(predicate); } List<Predicate> predicates02 = new ArrayList<>(1); if (!StringUtils.isEmpty(student.getSex())) { Predicate predicate = cb.equal(root.get("sex").as(String.class), student.getSex()); predicates02.add(predicate); } if (student.getTotal() != null) { Predicate predicate = cb.greaterThanOrEqualTo(root.get("total").as(Integer.class), student.getTotal()); predicates02.add(predicate); } Predicate predicate = cb.or(predicates02.toArray(new Predicate[predicates02.size()])); predicates.add(predicate); return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); }; List<Student> studentList = studentRepository.findAll(stuSpec); System.out.println(studentList); //[Student(id=2, name=李四, age=24, sex=男, total=179)] } } ```