Spring Data JPA in 查询例子

    /**
     * 查询所有客户
     *
     * @param customer
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(method = RequestMethod.POST, value = "/findAll")
    public @ResponseBody
    Iterable findAll(@RequestBody Customer customer) {       
        Pageable pageable = new PageRequest(customer.getPageNumber(), customer.getSize(), Sort.Direction.DESC,
                "creationTime");
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder cb) {
                List list = new ArrayList();                
                // 所属用户
                String userId = customer.getUserId();
                if (!StringUtils.isEmpty(userId)) {
                    if (userId.contains(",")) { // in查询
                        String[] ids = userId.split(",");
                        CriteriaBuilder.In in = cb.in(root.get("userId"));
                        for (int i = 0; i < ids.length; i++) {
                            in.value(ids[i]);
                        }
                        list.add(in);
                    } else { // 普通查询
                        list.add(cb.equal(root.get("userId").as(String.class), userId));
                    }
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
        return this.customerRepository.findAll(specification, pageable);
    } 
  

 

你可能感兴趣的:(Java)