spring data jpa 自定义条件查询 + 分页 + 排序

@Override
public Page queryBook(Book book, Pageable pageable) {
    return bookRepository.findAll(new Specification() {

        @Override
        public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
            List predicates = new ArrayList();

            if(!StringUtils.isEmpty(book.getName())) {
                predicates.add(cb.like(root.get("name"), "%" + book.getName() + "%"));

            }
            if(!StringUtils.isEmpty(book.getDescription())) {
                predicates.add(cb.like(root.get("description"), "%" + book.getDescription() + "%"));

            }
            if(!StringUtils.isEmpty(book.getAuthor())) {
                predicates.add(cb.equal(root.get("author"),book.getAuthor()));

            }

            query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
            query.orderBy(cb.desc(root.get("createTime").as(String.class)));

            return query.getRestriction();
        }

    }, pageable);
}

你可能感兴趣的:(spring)