1.引入jar包

  1. <dependency>
  2. <groupId>com.github.pagehelper</groupId>
  3. <artifactId>pagehelper-spring-boot-starter</artifactId>
  4. <version>${pagehelper.version}</version>
  5. </dependency>

2.yml配置

  1. pagehelper:
  2. helperDialect: mysql
  3. reasonable: true
  4. supportMethodsArguments: true
  5. params: count=countSql

3.封装相关分页方法

3.1分页参数类

  1. public class PageParam<T> implements Serializable {
  2. private static final long serialVersionUID = -7916211163897873899L;
  3. private int pageNum=1;
  4. private int pageSize=10;
  5. //条件参数
  6. private T param;
  7. //排序字段
  8. private String orderBy;
  9. public int getPageSize()
  10. {
  11. return pageSize;
  12. }
  13. public void setPageSize(int pageSize)
  14. {
  15. this.pageSize = pageSize;
  16. }
  17. public int getPageNum()
  18. {
  19. return pageNum;
  20. }
  21. public void setPageNum(int pageNum)
  22. {
  23. this.pageNum = pageNum;
  24. }
  25. public T getParam()
  26. {
  27. return param;
  28. }
  29. public void setParam(T param)
  30. {
  31. this.param = param;
  32. }
  33. public String getOrderBy()
  34. {
  35. return orderBy;
  36. }
  37. public void setOrderBy(String orderBy)
  38. {
  39. //需要注意sql注入
  40. this.orderBy = orderBy;
  41. }
  42. }

3.2分页结果类

  1. public class PagedList<T> implements Serializable
  2. {
  3. private static final long serialVersionUID = -1253790062865437768L;
  4. private int pageNum = 1;
  5. private List<T> data = null;
  6. private int pageCount = 0;
  7. private int recordCount = -1;
  8. private int pagingType = 0;
  9. private int pageSize;
  10. private String orderBy;
  11. /**
  12. * @return the pageSize
  13. */
  14. public int getPageSize()
  15. {
  16. return pageSize;
  17. }
  18. /**
  19. * @param pageSize
  20. * the pageSize to set
  21. */
  22. public void setPageSize(int pageSize)
  23. {
  24. if (pageSize <= 0)
  25. {
  26. return;
  27. }
  28. this.pageSize = pageSize;
  29. }
  30. /**
  31. * @return the pageCount
  32. */
  33. public int getPageCount()
  34. {
  35. return pageCount;
  36. }
  37. /**
  38. * @param pageCount
  39. * the pageCount to set
  40. */
  41. public void setPageCount(int pageCount)
  42. {
  43. if (pageCount <= 0)
  44. {
  45. return;
  46. }
  47. this.pageCount = pageCount;
  48. }
  49. /**
  50. * @return the recordCount
  51. */
  52. public int getRecordCount()
  53. {
  54. return recordCount;
  55. }
  56. /**
  57. * @param recordCount
  58. * the recordCount to set
  59. */
  60. public void setRecordCount(int recordCount)
  61. {
  62. this.recordCount = recordCount;
  63. calcPageCount();
  64. }
  65. private void calcPageCount()
  66. {
  67. if (this.recordCount < 0)
  68. {
  69. return;
  70. }
  71. int tmp = this.recordCount % getPageSize();
  72. this.pageCount = (tmp == 0 ? (this.recordCount / getPageSize())
  73. : (this.recordCount / getPageSize() + 1));
  74. if (this.pageNum > this.pageCount && this.pageCount != 0)
  75. {
  76. this.pageNum = this.pageCount;
  77. }
  78. this.pageNum = this.pageCount;
  79. }
  80. public void setData(List<T> data)
  81. {
  82. this.data = data;
  83. if (ObjectUtil.isNotEmpty(data) && this.recordCount == -1)
  84. {
  85. this.recordCount = data.size();
  86. }
  87. }
  88. public List<T> getData()
  89. {
  90. return data;
  91. }
  92. /**
  93. * @return the pagingType
  94. */
  95. public int getPagingType()
  96. {
  97. return pagingType;
  98. }
  99. /**
  100. * @param pagingType
  101. * the pagingType to set
  102. */
  103. public void setPagingType(int pagingType)
  104. {
  105. this.pagingType = pagingType;
  106. }
  107. public void setOrderBy(String orderBy)
  108. {
  109. this.orderBy = orderBy;
  110. }
  111. public int getPageNum()
  112. {
  113. return pageNum;
  114. }
  115. public void setPageNum(int pageNum)
  116. {
  117. this.pageNum = pageNum;
  118. }
  119. public String getOrderBy()
  120. {
  121. return orderBy;
  122. }
  123. }

3.3分页工具类

  1. public class PageUtils implements Serializable
  2. {
  3. private static final long serialVersionUID = 377943433889798799L;
  4. public static <T> PagedList<T> exportPagedList(PageParam<T> pageParam)
  5. {
  6. PagedList<T> pl = new PagedList<T>();
  7. // pagesize
  8. int pageSize = pageParam.getPageSize();
  9. if (pageSize <= 0)
  10. {
  11. pageSize = 10;
  12. }
  13. else
  14. {
  15. pl.setPageSize(pageSize);
  16. }
  17. int pageNum = pageParam.getPageNum();
  18. pl.setPageNum(pageNum);
  19. String orderBy= pageParam.getOrderBy();
  20. if(StringUtil.isNotEmpty(orderBy))
  21. {
  22. //防止sql注入
  23. String orderBySql=SQLFilter.sqlInject(orderBy);
  24. pl.setOrderBy(orderBySql);
  25. }
  26. return pl;
  27. }
  28. public static <T>PagedList<T> toPageList(PageInfo<T> spage)
  29. {
  30. PagedList<T> pagedList = new PagedList<T>();
  31. pagedList.setPageSize((int) spage.getPageSize());
  32. pagedList.setPageNum((int) spage.getPageNum());
  33. pagedList.setRecordCount((int) spage.getTotal());
  34. pagedList.setData(spage.getList());
  35. pagedList.setPageCount((int) spage.getPages());
  36. return pagedList;
  37. }
  38. }

3.4实例代码

  1. @PostMapping("getPageList")
  2. public Result getPageList(@RequestBody PageParam<TUser> pageParm) {
  3. //接收参数
  4. PagedList<TUser> pl =PageUtils.exportPagedList(pageParm);
  5. return Result.success(userService.queryPageList(pl, pageParm.getParam()));
  6. }
  7. public PagedList<TUser> queryPageList(PagedList<TUser> page,TUser user) {
  8. PageInfo<TUser> pageInfo= PageHelper.startPage(page).doSelectPageInfo(()-> list(user));
  9. //转换结果
  10. return PageUtils.toPageList(pageInfo);
  11. }

4.分页中的排序字段防止SQL注入

  1. String orderBy= pageParam.getOrderBy();
  2. if(StringUtil.isNotEmpty(orderBy))
  3. {
  4. //防止sql注入
  5. String orderBySql=SQLFilter.sqlInject(orderBy);
  6. pl.setOrderBy(orderBySql);
  7. }
  1. public class SQLFilter
  2. {
  3. public static String sqlInject(String str)
  4. {
  5. if (StringUtil.isBlank(str))
  6. {
  7. return null;
  8. }
  9. // 去掉'|"|;|\字符
  10. str = StringUtil.replace(str, "'", "");
  11. str = StringUtil.replace(str, "\"", "");
  12. str = StringUtil.replace(str, ";", "");
  13. str = StringUtil.replace(str, "\\", "");
  14. // 转换成小写
  15. str = str.toLowerCase();
  16. // 非法字符
  17. String[] keywords = { "master", "truncate", "insert", "select",
  18. "delete", "update", "declare", "alert", "drop" };
  19. // 判断是否包含非法字符
  20. for (String keyword : keywords)
  21. {
  22. if (str.indexOf(keyword) != -1)
  23. {
  24. throw new SysException("包含非法字符");
  25. }
  26. }
  27. return str;
  28. }
  29. }

5.复杂SQL语句需要自定义SQL的count语句

PageHelper实现分页,默认是查询自定义的count语句是否存在,如果存在就用自定义的语句,否则就在外层包装查询的语句,而自定义count语句只需要在在查询语句名称后面添加_COUNT即可。例如
查询集合的语句名称为queryPageList,那么查询count的语句为queryPageList_COUNT,返回Long类型即可。

  1. <select id="queryPageList_COUNT" resultType="java.lang.Long">
  2. select count(1) from t_user u
  3. left join t_user_role ur on ur.userOid=u.oid
  4. <where>
  5. <if test="name != null">name=#{name}</if>
  6. </where>
  7. </select>

6.分页失效的常见的场景

  1. pageHelper分页查询有个特殊的要求,查询下sql语句一定要紧跟在分页查询的后面,否则分页查询会失效。
  2. 注意pagehelper的reasonable 默认为false,遇到查询页数大于总页数时,出现分页失败

pagehelper的reasonable 默认为false,遇到查询页数大于总页数时,查询为空;当reasonable设置为true时,遇到查询页数大于总页数时,查询最后一页数据;

  1. PageHelper先开启分页,后对list数据操作将会导致分页错误

    public PageInfo<TUserVO> getUserPageList(int pageNum, int pageSize) {
     PageHelper.startPage(pageNum,pageSize);
     List<TUserVO> tUserVOsByView = userMapper.getUserList();
    
     List<TUserVO> TUserVOs = new ArrayList<>();
    
     for (TUserVO TUserVO : tUserVOsByView) {
         TUserVO TUserVOSingle = new TUserVO();
         TUserVOSingle.setHdId(TUserVO.getHdId());
         TUserVOs.add(TUserVOSingle);
     }
     PageInfo<TUserVO> pageViewInfo = new PageInfo<>(TUserVOs);
    
     return pageViewInfo;
    }
    
  2. PageHelper先对list数据操作,后开启分页,将会导致分页失效

    public PageInfo<TUserVO> getUserPageList(int pageNum, int pageSize) {       
     List<TUserVO> tUserVOsByView = userMapper.getUserList();
     List<TUserVO> TUserVOs = new ArrayList<>();
     for (TUserVO TUserVO : tUserVOsByView) {
         TUserVO TUserVOSingle = new TUserVO();
         TUserVOSingle.setHdId(TUserVO.getHdId());
     }
     PageHelper.startPage(pageNo,pageSize);
     PageInfo<TUserVO> pageViewInfo = new PageInfo<>(TUserVOs);
    
     return pageViewInfo;
    }