基于mybatisplus使用pagehelper实现简单分页查询的功能。pagehelper仅需要把已有查询结果重新封装一下即可,不需要改变sql、mapper之类的。例如有xxxmaper.findall(xx)函数可以列出全部符合条件的数据。仅需要
PageHelper.startPage(pageNum, pageSize);
List<Entity> list = xxxMapper.findall(xx);
return new PageInfo<>(list);
即可实现分页查询。
本文操作前提:拥有一个可以使用mybatisplus和数据库做交互的项目,这里使用了spring boot使用mybatisplus访问mysql的配置流程生成的项目。
1. 基于pagehelper的分页函数实现
1.1 添加依赖项并重新加载maven
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.7</version>
</dependency>
1.2 在service中定义拥有分页功能的方法,并在接口类中声明。
public PageInfo<User> queryByPage(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> list = userMapper.findall();
return new PageInfo<>(list);
}
2.其他部分内容
此时分页查询接口已经完全实现了,后续内容是为了测试而写的其它内容。
2.1. 在mapper中findall()方法接口
usermapper.java
usermapper.xml对应sql
<select id="findall" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
2.2.controller对应接口实现
@GetMapping("/list")
public PageInfo<User> getList(@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "10") int pageSize) {
PageInfo<User> infos = userService.queryByPage(pageNum, pageSize);
return infos;
}
结果查看
访问 localhost:8080/myuser/list?pageNum=1&pageSize=8
访问 localhost:8080/myuser/list?pageNum=1&pageSize=3