JPA ((A and B) or (C and D)) and E and F

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);
    }

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值