一、PageHelper的配置加载及使用
1.1 配置
参考地址 https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
在 pom.xml 中添加如下依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.1</version>
</dependency>
在 yml 配置文件中添加如下依赖:
pagehelper:
helperDialect: mysql #数据库类型,不指定的话会解析 datasource.url进行配置
supportMethodsArguments: true
params: count=countSql
1.2 启动加载流程
SpringBoot项目启动时pagehelper的加载流程
1.加载配置
@Configuration
@ConditionalOnBean({
SqlSessionFactory.class})
@EnableConfigurationProperties({
PageHelperProperties.class})
@AutoConfigureAfter({
MybatisAutoConfiguration.class})
@Lazy(false)
// 配置类,会在项目启动时加载此类
public class PageHelperAutoConfiguration implements InitializingBean {
// 实例化 PageInterceptor 拦截器
public void afterPropertiesSet() throws Exception {
PageInterceptor interceptor = new PageInterceptor();
interceptor.setProperties(this.properties);
Iterator var2 = this.sqlSessionFactoryList.iterator();
while(var2.hasNext()) {
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)var2.next();
org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
if (!this.containsInterceptor(configuration, interceptor)) {
configuration.addInterceptor(interceptor);
}
}
}
}
2.设置属性
@ConfigurationProperties(
prefix = "pagehelper"
)
// 配置属性
public class PageHelperProperties extends Properties {
}
3.创建拦截器
// 拦截器 继承了myabtis的拦截器
public class PageInterceptor implements Interceptor {
// 构造方法 读取配置输出banner
public PageInterceptor() {
String bannerEnabled = System.getProperty("pagehelper.banner");
if (StringUtil.isEmpty(bannerEnabled)) {
bannerEnabled = System.getenv("PAGEHELPER_BANNER");
}
if (StringUtil.isEmpty(bannerEnabled) || Boolean.parseBoolean(bannerEnabled)) {
log.debug("...");
}
}
// 核心拦截方法
public Object intercept(Invocation invocation) throws Throwable {
// 代码省略....
}
// 统计方法
private Long count(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
// 代码省略....
}
// 读取配置,设置属性
public void setProperties(Properties properties) {
this.msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
// 如果没有配置dialect属性的话,会默认实例化PageHelper类
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass