JPA 实现分页查询的两种方式

1.使用ExampleMatcher

ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("userId", match -> match.exact()) //精确匹配userId
                .withIgnorePaths("id");//忽略属性:是否关注。因为是基本类型,需要忽略掉
ShareRecord shareRecord = new ShareRecord();
shareRecord.setUserId(userId);
Example of = Example.of(shareRecord, matcher);
pageable  = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), pageable.getSort());
Page page = shareRecordRepository.findAll(of,pageable);

2.使用Specification

Page page = shareRecordRepository.findAll(new Specification(){
   @Override
   public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
       List list = new ArrayList<>();
          if (StringUtils.isNotEmpty(userId))
              list.add(cb.equal(root.get("userId"), userId));
          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()));

你可能感兴趣的:(JPA 实现分页查询的两种方式)