1、在pom文件中引入Pagehelper分页插件,编辑pom.xml
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
2、配置分页插件,编辑application.properties,添加如下配置
#分页插件
pagehelper.helper-dialect=mysql
pagehelper.params=count=countSql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
3、修改controller代码
@GetMapping("")
public ReturnResult index() {
PageHelper.startPage(1, 1);
List<UserBean> list = userService.getUsers();
PageInfo<UserBean> userBeanPageInfo = new PageInfo<>(list);
return ReturnResult.data(userBeanPageInfo, "获取用户列表成功");
}
其中: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 | 是否有下一页 |
注意:mapper.xml文件中的sql语句最后不要添加;,否则会报错。
如果查看sql时发现只有一个参数,可能是因为pageNum传入了1
本文介绍了如何在Spring Boot应用中通过PageHelper插件配置分页,包括在pom.xml中引入依赖、application.properties中配置参数,并展示了如何在Controller中调用并返回PageInfo。
1万+

被折叠的 条评论
为什么被折叠?



