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 超简单分页实现

提供最优质的资源集合

立即查看 了解详情