1.引入jar包
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>${pagehelper.version}</version></dependency>
2.yml配置
pagehelper:helperDialect: mysqlreasonable: truesupportMethodsArguments: trueparams: count=countSql
3.封装相关分页方法
3.1分页参数类
public class PageParam<T> implements Serializable {private static final long serialVersionUID = -7916211163897873899L;private int pageNum=1;private int pageSize=10;//条件参数private T param;//排序字段private String orderBy;public int getPageSize(){return pageSize;}public void setPageSize(int pageSize){this.pageSize = pageSize;}public int getPageNum(){return pageNum;}public void setPageNum(int pageNum){this.pageNum = pageNum;}public T getParam(){return param;}public void setParam(T param){this.param = param;}public String getOrderBy(){return orderBy;}public void setOrderBy(String orderBy){//需要注意sql注入this.orderBy = orderBy;}}
3.2分页结果类
public class PagedList<T> implements Serializable{private static final long serialVersionUID = -1253790062865437768L;private int pageNum = 1;private List<T> data = null;private int pageCount = 0;private int recordCount = -1;private int pagingType = 0;private int pageSize;private String orderBy;/*** @return the pageSize*/public int getPageSize(){return pageSize;}/*** @param pageSize* the pageSize to set*/public void setPageSize(int pageSize){if (pageSize <= 0){return;}this.pageSize = pageSize;}/*** @return the pageCount*/public int getPageCount(){return pageCount;}/*** @param pageCount* the pageCount to set*/public void setPageCount(int pageCount){if (pageCount <= 0){return;}this.pageCount = pageCount;}/*** @return the recordCount*/public int getRecordCount(){return recordCount;}/*** @param recordCount* the recordCount to set*/public void setRecordCount(int recordCount){this.recordCount = recordCount;calcPageCount();}private void calcPageCount(){if (this.recordCount < 0){return;}int tmp = this.recordCount % getPageSize();this.pageCount = (tmp == 0 ? (this.recordCount / getPageSize()): (this.recordCount / getPageSize() + 1));if (this.pageNum > this.pageCount && this.pageCount != 0){this.pageNum = this.pageCount;}this.pageNum = this.pageCount;}public void setData(List<T> data){this.data = data;if (ObjectUtil.isNotEmpty(data) && this.recordCount == -1){this.recordCount = data.size();}}public List<T> getData(){return data;}/*** @return the pagingType*/public int getPagingType(){return pagingType;}/*** @param pagingType* the pagingType to set*/public void setPagingType(int pagingType){this.pagingType = pagingType;}public void setOrderBy(String orderBy){this.orderBy = orderBy;}public int getPageNum(){return pageNum;}public void setPageNum(int pageNum){this.pageNum = pageNum;}public String getOrderBy(){return orderBy;}}
3.3分页工具类
public class PageUtils implements Serializable{private static final long serialVersionUID = 377943433889798799L;public static <T> PagedList<T> exportPagedList(PageParam<T> pageParam){PagedList<T> pl = new PagedList<T>();// pagesizeint pageSize = pageParam.getPageSize();if (pageSize <= 0){pageSize = 10;}else{pl.setPageSize(pageSize);}int pageNum = pageParam.getPageNum();pl.setPageNum(pageNum);String orderBy= pageParam.getOrderBy();if(StringUtil.isNotEmpty(orderBy)){//防止sql注入String orderBySql=SQLFilter.sqlInject(orderBy);pl.setOrderBy(orderBySql);}return pl;}public static <T>PagedList<T> toPageList(PageInfo<T> spage){PagedList<T> pagedList = new PagedList<T>();pagedList.setPageSize((int) spage.getPageSize());pagedList.setPageNum((int) spage.getPageNum());pagedList.setRecordCount((int) spage.getTotal());pagedList.setData(spage.getList());pagedList.setPageCount((int) spage.getPages());return pagedList;}}
3.4实例代码
@PostMapping("getPageList")public Result getPageList(@RequestBody PageParam<TUser> pageParm) {//接收参数PagedList<TUser> pl =PageUtils.exportPagedList(pageParm);return Result.success(userService.queryPageList(pl, pageParm.getParam()));}public PagedList<TUser> queryPageList(PagedList<TUser> page,TUser user) {PageInfo<TUser> pageInfo= PageHelper.startPage(page).doSelectPageInfo(()-> list(user));//转换结果return PageUtils.toPageList(pageInfo);}
4.分页中的排序字段防止SQL注入
String orderBy= pageParam.getOrderBy();if(StringUtil.isNotEmpty(orderBy)){//防止sql注入String orderBySql=SQLFilter.sqlInject(orderBy);pl.setOrderBy(orderBySql);}
public class SQLFilter{public static String sqlInject(String str){if (StringUtil.isBlank(str)){return null;}// 去掉'|"|;|\字符str = StringUtil.replace(str, "'", "");str = StringUtil.replace(str, "\"", "");str = StringUtil.replace(str, ";", "");str = StringUtil.replace(str, "\\", "");// 转换成小写str = str.toLowerCase();// 非法字符String[] keywords = { "master", "truncate", "insert", "select","delete", "update", "declare", "alert", "drop" };// 判断是否包含非法字符for (String keyword : keywords){if (str.indexOf(keyword) != -1){throw new SysException("包含非法字符");}}return str;}}
5.复杂SQL语句需要自定义SQL的count语句
PageHelper实现分页,默认是查询自定义的count语句是否存在,如果存在就用自定义的语句,否则就在外层包装查询的语句,而自定义count语句只需要在在查询语句名称后面添加_COUNT即可。例如
查询集合的语句名称为queryPageList,那么查询count的语句为queryPageList_COUNT,返回Long类型即可。
<select id="queryPageList_COUNT" resultType="java.lang.Long">select count(1) from t_user uleft join t_user_role ur on ur.userOid=u.oid<where><if test="name != null">name=#{name}</if></where></select>
6.分页失效的常见的场景
- pageHelper分页查询有个特殊的要求,查询下sql语句一定要紧跟在分页查询的后面,否则分页查询会失效。
- 注意pagehelper的reasonable 默认为false,遇到查询页数大于总页数时,出现分页失败
pagehelper的reasonable 默认为false,遇到查询页数大于总页数时,查询为空;当reasonable设置为true时,遇到查询页数大于总页数时,查询最后一页数据;
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; }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; }
