SQL如下
SELECT * FROM USER t WHERE (t.age=18 AND t.gender='女') OR (t.height=180 AND t.gender='男') AND t.face_score=9 AND t.salary=10000;
用JPA实现
@Test
public void testSpec1() {
Specification<User> spec = new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicateList = new ArrayList<Predicate>();
List<Predicate> girlPredicate = new ArrayList<Predicate>();
girlPredicate.add(criteriaBuilder.equal(root.get("age"), "18"));//年龄18
girlPredicate.add(criteriaBuilder.equal(root.get("gender"), "女"));//性别女
List<Predicate> boyPredicate = new ArrayList<Predicate>();
boyPredicate.add(criteriaBuilder.equal(root.get("height"), "180"));//身高一米八
boyPredicate.add(criteriaBuilder.equal(root.get("gender"), "男"));//性别男
predicateList.add(criteriaBuilder.equal(root.get("faceScore"), "9"));//颜值9分
predicateList.add(criteriaBuilder.equal(root.get("salary"), "10000"));//月入过万
predicateList.add(criteriaBuilder.or(criteriaBuilder.and(girlPredicate.toArray(new Predicate[0])), criteriaBuilder.and(boyPredicate.toArray(new Predicate[0]))));
return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
}
};
List<User> users = userDao.findAll(spec);
}