spring data jpa 的 in 查询 Specification 实现

只是一个简单需求:  查询所有部门id 属于  idList 的数据

 Page page = workWeightRepository.findAll(new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                List list = new ArrayList<>();

                if(null != subDepartmentId && !"".equals("subDepartmentId")){
                    list.add(cb.equal(root.get("subDepartmentId"), subDepartmentId));
                }
                if(null != status && !"".equals("status")){
                    list.add(cb.equal(root.get("status"), status));
                }
                if (null != startTime && !"".equals("startTime")) {
                    list.add(cb.greaterThanOrEqualTo(root.get("startTime"), DateUtil.stringToDate(startTime)));
                }
                if (null != endTime && !"".equals("endTime")) {
                    list.add(cb.lessThanOrEqualTo(root.get("endTime"), DateUtil.stringToDate(endTime)));
                }
                Expression exp = root.get("departmentId");
                list.add(exp.in(idList)); // 往in中添加所有id 实现in 查询

                if (list.size() != 0) {
                    Predicate[] p = new Predicate[list.size()];
                    return cb.and(list.toArray(p));
                } else {
                    return null;
                }
            }
        }, new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort()));
重点代码:

  Expression exp = root.get("departmentId");
                list.add(exp.in(idList)); // idList是部门id集合, 实现in 查询


你可能感兴趣的:(框架)