首页 > 其他 > 详细

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

时间:2019-12-17 15:31:57      阅读:83      评论:0      收藏:0      [点我收藏+]

1.使用ExampleMatcher

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

2.使用Specification

Page<ShareRecord> page = shareRecordRepository.findAll(new Specification<ShareRecord>(){
   @Override
   public Predicate toPredicate(Root<ShareRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
       List<Predicate> list = new ArrayList<>();
          if (StringUtils.isNotEmpty(userId))
              list.add(cb.equal(root.<String>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 实现分页查询的两种方式

原文:https://www.cnblogs.com/snail-gao/p/12054749.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!