说明
- pagehelper说明:数据库数据分页插件
- pagehelper官网:https://pagehelper.github.io/
- 使用前提:搭好springboot mybatis运行环境,要有数据库和用于测试的数据库表
- 注意:以下是springboot下使用pagehelper
依赖
-
注意:spring-boot-starter-parent的版本要和pagehelper-spring-boot-starter版本匹配(个人使用的是springboot 2.6.7版本和pagehelper1.4.2版本)
-
版本不匹配的报错:
Error creating bean with name com.github.pagehelper.autoconfigure.PageHelperAutoConfiguration
<!-- SpringBoot使用PageHelper分页控件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
配置
- 文件:application.yaml
# MyBatis使用pageHelper分页
pagehelper:
# 方言:决定pagehelper生成哪种sql语句
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
测试
@SpringBootTest
public class PageHelperTest {
@Autowired
UserMapper userMapper;
@Test
public void test(){
//紧跟在PageHelper.startPage方法后的第一个Mybatis的查询(Select)方法会被分页。
PageHelper.startPage(1,5);
List<User> users = userMapper.getAllUser();
users.forEach(System.out::println);
}
}
关于PageHelper
注意
(1)不支持带有update
语句分页
对于带有for update
的sql,会抛出运行时异常,对于这样的sql建议手动分页,毕竟这样的sql需要重视。
(2)不支持嵌套结果映射
由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。