Spring Data JPA 超简单分页实现

1.最原始的分页:
Repository:
Page<Product> findAll(Specification<Product> specification, Pageable pageable);

Controller:
public String findAll(HttpServletRequest request) {
 int pageNum = Integer.parseInt(request.getParameter("pageNum"));
 int pageSize = Integer.parseInt(request.getParameter("pageSize"));
 final String searchString = request.getParameter("searchString");
 logger.info("---pageNumber:" + pageNum + "---pageSize:" + pageSize + "--searchString:" + searchString);
 // PageAble 接口通常用的是PageRequest实现类,其中封装了需要分页的信息
 // 排序相关的,sor封装了排序的信息
 Sort.Order order1 = new Sort.Order(Sort.Direction.ASC, "id");
 Sort sort = new Sort(order1);
 Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
 Specification<Product> specification = new Specification<Product>() {
 @Override
 public Predicate toPredicate(Root<Product> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
 Predicate p = null;
 if (searchString != null || !searchString.equalsIgnoreCase("")) {
 p = cb.like(root.get("description").as(String.class), "%" + searchString + "%"); //分页查询条件
 }
 return p;
 }
 };
 Page<Product> allPage = productRepository.findAll(specification, pageable);
 logger.info("=====All:" + JSON.toJSONString(allPage));
 return JSON.toJSONString(allPage);
2.最简单的分页,使用jpa自带的Page

Repository:无需写,自带
Controller: 如下一句话,page和size是前端传过来的值
Page<Commodity> all = commodityDao.findAll(new PageRequest(page, size));

3.最简单的分页,带查询条件的分页
Repository:
@Query(value = "select * from Commodity C where C.name like CONCAT('%',:name,'%')  ORDER BY ?#{#pageable}",
        countQuery = "SELECT count(*) FROM Commodity C where C.name like CONCAT('%',:name,'%') ",
        nativeQuery = true)
Page<Commodity> findByName(@Param("name") String name, Pageable pageable);
Controller:
Page<Commodity> pages=commodityDao.findByName(name, new PageRequest(page, size));

本站的文章多是老王开发工作中问题的记录,一个字一个字敲的,切实可行,可以分享,需要留个原文链接,至少也意思意思吧!
阿里云服务器怎么购买划算-vsalw技术博客 » Spring Data JPA 超简单分页实现

每个人都是以自己独特的方式体味生活,或许别人不理解,但自己知道:其中的酸甜苦辣就叫做幸福!

认同! 瞎扯淡!