1.common-center的pom引入依赖
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
2.修改配置文件bootstarp.yml,添加pagehelper相关参数
# pagehelper相关
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
3.整理PagehelperResult工具类(根据数据格式需求)
package com.ruyi.common;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java.util.HashMap;
import java.util.List;
public class PageHelperResult {
/**
* 封装PageHelper分页结果
* @param list
* @return
*/
public static HashMap<String, Object> ResultMap(List list){
PageInfo<Object> pageInfo = new PageInfo(list);
long total = pageInfo.getTotal();
HashMap<String, Object> resultMap = new HashMap<>(2);
resultMap.put("totalCount",total);
resultMap.put("info",list);
PageHelper.clearPage();
return resultMap;
}
}
4.修改已有方法,添加相关代码
/**
* 后台用户列表
* @return
*/
@RequestMapping(value = "/getAdminUserList", method = RequestMethod.POST)
@ApiOperation(value = "后台管理用户列表", notes = "获得所有后台管理用户列表", produces = "application/json")
public Result getAdminUserList(@RequestBody JSONObject jsonObject){
Integer userId = jsonObject.getInteger("id");
Integer pageNum = jsonObject.getInteger("pageNum");
Integer pageSize = jsonObject.getInteger("pageSize");
logger.info("传入参数为:[ {} ]",jsonObject);
PageHelper.startPage(pageNum,pageSize);
List<AdminUser> adminUserList = userService.getAdminUserList(userId);
HashMap<String, Object> resultMap = PageHelperResult.ResultMap(adminUserList);
logger.info("输出参数为:[ {} ]",resultMap);
return Result.success(resultMap);
}
其中:
PageHelper.startPage(int PageNum,int PageSize):用来设置页面的位置和展示的数据条目数,我们设置每页展示5条数据。
PageInfo用来封装页面信息,返回给前台界面。
PageInfo中的一些我们需要用到的参数如下表:
PageInfo.list | 结果集 |
PageInfo.pageNum | 当前页码 |
PageInfo.pageSize | 当前页面显示的数据条目 |
PageInfo.pages | 总页数 |
PageInfo.total | 数据的总条目数 |
PageInfo.prePage | 上一页 |
PageInfo.nextPage | 下一页 |
PageInfo.isFirstPage | 是否为第一页 |
PageInfo.isLastPage | 是否为最后一页 |
PageInfo.hasPreviousPage | 是否有上一页 |
PageHelper.hasNextPage | 是否有下一页 |
扩展:
以下摘自网络:https://blog.csdn.net/wxr15732623310/article/details/79242760
注意:分页不安全的情况
PageHelper 方法使用了静态的 ThreadLocal 参数,分页参数和线程是绑定的。
只要你可以保证在 PageHelper 方法调用后紧跟 MyBatis 查询方法,这就是安全的。因为 PageHelper 在 finally 代码段中自动清除了 ThreadLocal 存储的对象。
这种情况下由于 param1 存在 null 的情况,就会导致 PageHelper 生产了一个分页参数,但是没有被消费,这个参数就会一直保留在这个线程上。当这个线程再次被使用时,就可能导致本不该分页的方法去消费了这个分页参数,这就产生了莫名其妙的分页。
如下代码是不安全的:
PageHelper.startPage(1, 10);
List<Country> list;
if(param1 != null){
list = countryMapper.selectIf(param1);
} else {
list = new ArrayList<Country>();
}
写成如下便安全了:
List<Country> list;
if(param1 != null){
PageHelper.startPage(1, 10);
list = countryMapper.selectIf(param1);
} else {
list = new ArrayList<Country>();
}
另外也可以手动清理ThreadLocal存储的分页参数:
PageHelper.clearPage();