赞
踩
后端开发80%都是查询操作, 而查询经常涉及到数据分页, 分页工具有很多, 本文介绍的是分页插件PageHelper, 工程基于springboot
参考文章: springBoot mybatis整合pageHelper
1.导包
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
2.YML配置
pagehelper:
autoRuntimeDialect: true
reasonable: true
supportMethodsArguments: true
params: count=countSql
3.分页使用示例
controller层
@RestController
@RequestMapping("/pageHelperTest/")
public class PageHelperTest{
@Autowired
private UserService userService;
@RequestMapping("/pageHelperTest/{pageNum}/{pageSize}")
public PageInfo<User> pageHelperTest(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
//调用方法进行分页查询
return userService.findAll(pageNum, pageSize);
}
}
service层
@Service
public class UserService{
@Autowired
private UserMapper userMapper;
public PageInfo<User> findAll(int pageNum, int pageSize) {
// 设置分页参数; pageNum:页码, pageSize:每页大小
PageHelper.startPage(pageNum,pageSize);
// 执行sql查询方法查询所有数据, 会自动分页
List<User> list = userMapper.findAll();
return new PageInfo<User>(list);
}
}
返回json结果示例
{ "pageNum": 3, "pageSize": 3, "size": 3, "startRow": 7, "endRow": 9, "total": 10, "pages": 4, "list": [ { "id": 9, "username": "bajie", "password": "123456", "createTime": "2019-06-21T16:00:00.000+0000", "trueName": "猪八戒", "remarks": null, "bz": null }, { "id": 10, "username": "wukong", "password": "123456", "createTime": "2019-06-21T16:00:00.000+0000", "trueName": "孙悟空", "remarks": null, "bz": null }, { "id": 11, "username": "shasheng", "password": "123456", "createTime": "2019-06-21T16:00:00.000+0000", "trueName": "沙悟净", "remarks": null, "bz": null } ], "prePage": 2, "nextPage": 4, "isFirstPage": false, "isLastPage": false, "hasPreviousPage": true, "hasNextPage": true, "navigatePages": 8, "navigatepageNums": [ 1, 2, 3, 4 ], "navigateFirstPage": 1, "navigateLastPage": 4, "firstPage": 1, "lastPage": 4 }
4.解释
其中:PageHelper.startPage(int PageNum,int PageSize):用来设置页面的位置和展示的数据条目数,我们设置每页展示5条数据。PageInfo用来封装页面信息,返回给前台界面。PageInfo中的一些我们需要用到的参数如下表:
三.参考
Springboot Mybatis使用pageHelper实现分页查询
Spring Boot入门,整合Pagehelper分页插件
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。