spring JPA分页排序条件查询

时间:2021-01-09 02:55:00
@RequestMapping("/listByPage")
    public Page<Production> listByPage(int page, int size, String sortStr, boolean sortAscOrDesc, String searchObj)
    {
        Specification<Production> specification = getSpecification(searchObj);

        if (StringUtils.isEmpty(sortStr))
        {
            return productionRepository.findAll(specification, new PageRequest(page, size));
        }
        else
        {
            return productionRepository.findAll(specification, new PageRequest(page, size, new Sort((sortAscOrDesc ? Sort.Direction.ASC : Sort.Direction.DESC), sortStr)));
        }
    }

    private Specification getSpecification(String searchObj)
    {
        JSONObject search = (JSONObject) JSONValue.parse(searchObj);

        Specification<Production> specification = new Specification<Production>()
        {
            @Override
            public Predicate toPredicate(Root<Production> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder)
            {
                List<Predicate> queryList = new ArrayList<Predicate>();

                if (search.get("name") != null && !StringUtils.isEmpty(search.get("name") + ""))
                {
                    queryList.add(criteriaBuilder.equal(root.get("name"), search.get("name") + ""));
                }
                if (search.get("name1") != null && !StringUtils.isEmpty(search.get("name1") + ""))
                {
                    queryList.add(criteriaBuilder.equal(root.get("name1"), search.get("name1") + ""));
                }

                if (queryList.size() > 0)
                {
                    criteriaQuery.where(queryList.toArray(new Predicate[queryList.size()]));
                }

                return criteriaQuery.getRestriction();
            }
        };

        return specification;
    }