spring data jpa分页

controller层

 1 @RequestMapping(value="/search")
 2     @ResponseBody
 3     public String search(HttpServletRequest request,int pageIndex,int size) {
 4         HttpSession session = request.getSession();
 5         User user = (User)session.getAttribute("user");
 6         Page<Message> page = onlineMessageService.pageFind(user,pageIndex, size);
 7         Map<String, Object> tableMap = new HashMap<String, Object>();
 8         tableMap.put("total", page.getTotalElements());
 9         tableMap.put("messages", page.getContent());
10         return ResponseJSON.instance().setData(tableMap).toJSON();
11 
12     }

service层

 1 @Transactional
 2     public Page<Message> pageFind(final User user,int pageIndex,int size) {
 3         Specification<Message> messgeSpeci = new Specification<Message>() {
 4             @Override
 5             public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
 6                 List<Predicate> predicates = new ArrayList<Predicate>();
 7                 predicates.add(cb.equal(root.get("user").<String>get("status"),"1"));
 8                 predicates.add(cb.equal(root.<String> get("isOnlineRead"),"0"));
 9                 query.where(predicates.toArray(new Predicate[] {}));
10                 return null;
11             }
12         };
13         return MessageRepository.findAll(messgeSpeci, new PageRequest(pageIndex,size));
14     }

 持久层接口继承

1 public interface MessageRepository extends JpaRepository<Message, Long> ,JpaSpecificationExecutor<Message>{.....}

 

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。