解决分页插件pagehelper在SpringBoot不起作用的问题
作者:博学的刘二胖
这篇文章主要介绍了解决分页插件pagehelper在SpringBoot不起作用的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
分页插件pagehelper在SpringBoot不起作用
在springBoot中使用分页插件pagehelper之后,在前端将数据拿出来的时候发现分页插件并没有起到作用?
检查之后发现在springBoot中如果需要使用分页插件需要添加pagehelper-spring-boot-starter的jar包才可生效。
springBoot版本:2.7.0
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>PageHelper在SpringBoot中的应用
1.POM文件
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2. pageHelper拦截器的了解
PageHelper就是实现了一个MyBatis的自定义拦截器
//@Intercepts:标识该类是一个自定义拦截器
//@Signature:指明我们需要拦截的接口和方法
/** type :mybatis 拦截器默认可拦截的类型只有四种,即四种接口类型 Executor、StatementHandler、ParameterHandler 和 ResultSetHandler
* 对于我们的自定义拦截器必须使用 mybatis 提供的注解来指明我们要拦截的是四类中的哪一个类接口
* method : 对应接口中的哪类方法
args :指明参数类型,从而确定是哪一个方法
*/
@Intercepts({@Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class PageInterceptor implements Interceptor {
protected Cache<String, MappedStatement> msCountMap = null;
private Dialect dialect;
private String default_dialect_class = "com.github.pagehelper.PageHelper";
private Field additionalParametersField;
private String countSuffix = "_COUNT";
3.配置文件中添加拦截器
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 使用下面的方式配置参数,参数介绍参考官方文档 -->
<!-- <property name="param1" value="value1"/>-->
</plugin>
</plugins>
</configuration>
4.pageHelper使用
/*doSelectPageInfo方法解释 : 是PageHelper.startPage()函数返回的默认Page实例内置的函数,该函数可以用以Lambda的形式通过额外的Function来进行查询而不需要再进行多余的PageInfo与List转换,而doSelectPageInfo的参数则是PageHelper内置的Function(ISelect)接口用以达到转换PageInfo的目的
*/
PageInfo</*返回类型*/> objectPageInfo = PageHelper.startPage( /*参数页码, 参数页面长度*/)
.doSelectPageInfo(() -> /*mysql数据查询:mapper.XXXX(参数)*/);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
