Springboot+jpa之 Specification复杂查询2:And查询和Or查询的组合以及In查询使用

本文介绍了在Springboot+jpa中如何使用Specification进行复杂的查询操作,包括And查询、Or查询的组合使用,以及In查询的应用。重点在于And查询的优先级高于Or查询,并提供了当Or查询条件为单个时,实际转化为And查询的逻辑。同时,文章展示了如何实现In查询,通过示例展示了根据用户deptId查询属于特定集合的数据。
摘要由CSDN通过智能技术生成

and和or组合重点代码:

       List<Predicate> tempAnd = new ArrayList<>(); //临时查询条件and
       List<Predicate> tempOr = new ArrayList<>(); //临时查询条件or

        if (!StringUtils.isNullOrEmpty(user.getDeptId()) && user.getDeptId() != 0) {

                 //查询条件1:用户部门ID与查询的部门ID一致
                 tempOr.add(cb.equal(deptId, user.getDeptId()));

                 //查询条件2:用户名与查询用户名一致
                 tempOr.add(cb.equal(userName,user.getUserName));
         }

        //复杂查询:and和or的组合使用
        //1.定义一个Predicate数组
        Predicate[] array_and = new Predicate[tempAnd.size()]; 
       
        //2.将and查询的条件添加到数组中
        Predicate Pre_And = cb.and(tempAnd.toArray(array_and)); 
        
        //3.再定义一个数组
        Predicate[] arrayOr = new Predicate[tempOr.size()];
        
        //4.将or查询的条件添加到数组中
        Predicate Pre_Or = cb.or(tempOr.toArray(arrayOr)); 


        //构建组合查询条件
        query.where(Pre_And, Pre_Or);

        return query.getRestriction();

 

  • 注意,and的优先级高于or,并且or条件如果只有一个查询条件,只会构成and条件
  • 前提:有三个条件(a,b,c) select u.* from user u where
  • 使用and条件 where后面添加的条件为: a and b and c
  • 使用or条件,只有一个条件a ,where 后面条件的条件为 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值