springboot中使用其他组件都是基于自动配置的AutoConfiguration配置累的,pagehelper插件也是一样的,通过PageHelperAutoConfiguration的,这个类存在于jar包的spring.factories

文件中,当springboot启动时会通过selector自动将配置类加载到上下文中

springboot集成pagehelper,pom依赖:

        <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-autoconfigure</artifactId> ---作用自动配置pagehelper
<version>1.2.3</version>
</dependency>

关键类:

PageHelperAutoConfiguration.java

package com.github.pagehelper.autoconfigure;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties; /**
* 自定注入分页插件
*
* @author liuzh
*/
@Configuration //表明当前了是一个配置类
@ConditionalOnBean(SqlSessionFactory.class)//当有SqlSesionFactory这个类的时候才实例化当前类
@EnableConfigurationProperties(PageHelperProperties.class)//pagehelpser的配置文件
@AutoConfigureAfter(MybatisAutoConfiguration.class)//当前类是在mybatisAutoconfiguration配置类初始化之后才初始化
public class PageHelperAutoConfiguration { @Autowired
private List<SqlSessionFactory> sqlSessionFactoryList; @Autowired
private PageHelperProperties properties;//配置文件 /**
* 接受分页插件额外的属性
*
* @return
*/
@Bean
@ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX)//将配置文件实例化为properties
public Properties pageHelperProperties() {
return new Properties();
} @PostConstruct//实例化之后条用当前方法,将pagehelper插件添加到myabtis的核心配置文件中(Configuration中) PageInterceptor就是pagehelper的插件
public void addPageInterceptor() {
PageInterceptor interceptor = new PageInterceptor();
Properties properties = new Properties();
//先把一般方式配置的属性放进去
properties.putAll(pageHelperProperties());
//在把特殊配置放进去,由于close-conn 利用上面方式时,属性名就是 close-conn 而不是 closeConn,所以需要额外的一步
properties.putAll(this.properties.getProperties());
interceptor.setProperties(properties);
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
}
} }

进一步看PageInterceptor.java,这个类就是mybatis的插件,先看类上的注解,@Interceptos注解表名当前类是一个拦截器,里边会有@Signature注解,这个注解主要配置的就是拦截的方法,如type:拦截的类是Executor,method:拦截的方法,args:拦截方法

的参数

@Intercepts(//这个注解是mybatis中的注解
{
@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 {
//缓存count查询的ms
protected Cache<String, MappedStatement> msCountMap = null;
private Dialect dialect;//这个是pagehelper的一个接口,里边有数据库的一些方言配置
private String default_dialect_class = "com.github.pagehelper.PageHelper";//默认的方言实现类,如果上边那个dialect没有配置的话,默认走这个
private Field additionalParametersField;
private String countSuffix = "_COUNT";

Dialect的一些实现类,不同的数据库使用不同的实现类,其中,pagehelper是默认的方言(这个类是在没有配置其他方言的时候,默认实例化的)

PageInterceptor类中的关键方法:intercept拦截方法,当拦截到相应的方法后,后走该改法判断时候需要改变

@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();//获取拦截到的方法的所有参数 下边获取0,1,2,3是进行强制转换对应的类,这个是根据@intercepts注解中的@sisignature中的args得到的
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次 分两种情况4个参数和6个参数也是根据注解@signature的args类判断的
if(args.length == 4){
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果 例如dialect使用的是默认的实现类的话,判断是否要跳过分页,是根据代码中查询数据库是,是否执行过PageHelper.startPage()方法类判断的(一种情况),执行过,则要分页,否则不分页
if (!dialect.skip(ms, parameter, rowBounds)) {
//反射获取动态参数
String msId = ms.getId();
Configuration configuration = ms.getConfiguration();
Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
          //下边会进行两步:1、总数查询 2、分页查询
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
String countMsId = msId + countSuffix;
Long count;
//先判断是否存在手写的 count 查询
MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);
if(countMs != null){
count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
} else {
countMs = msCountMap.get(countMsId);
//自动创建
if (countMs == null) {
//根据当前的 ms 创建一个返回值为 Long 类型的 ms
countMs = MSUtils.newCountMappedStatement(ms, countMsId);
msCountMap.put(countMsId, countMs);
}
count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);
}
//处理查询总数
//返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
//判断是否需要进行分页查询
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter);
//设置动态参数
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//执行分页查询
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不执行分页的情况下,也不执行内存分页
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
}

例子:

        Page<TUser> startPage = PageHelper.startPage(1, 2);
List<TUser> list1 = mapper.selectByEmailAndSex1(params);

//在查询数据库之前先执行startPage方法,传入分页参数进入starepage方法(这个方法在pagehelper的父类pagemethod中),startPage方法有多个重载的方法,该例子中用的是两个参数的

 /**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
*/
public static <E> Page<E> startPage(int pageNum, int pageSize) {
return startPage(pageNum, pageSize, true);
}
   /**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {
return startPage(pageNum, pageSize, count, null, null);
}
   /**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
* @param reasonable 分页合理化,null时用默认配置
* @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page<E> page = new Page<E>(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();//查询ThreadLocal中是否已经有了page
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}

springboot中的mybatis是如果使用pagehelper的的更多相关文章

  1. springboot中使用mybatis的分页插件pageHelper

    首先在pom.xml中配置 <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot ...

  2. SpringBoot中关于Mybatis使用的三个问题

    SpringBoot中关于Mybatis使用的三个问题 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8495453.html 原本是要讲讲PostgreSQL ...

  3. springboot中使用mybatis显示执行sql

    springboot 中使用mybatis显示执行sql的配置,在properties中添加如下 logging.你的包名=debug 2018-11-27 16:35:43.044 [DubboSe ...

  4. 在springboot中集成mybatis开发

    在springboot中利用mybatis框架进行开发需要集成mybatis才能进行开发,那么如何在springboot中集成mybatis呢?按照以下几个步骤就可以实现springboot集成myb ...

  5. 在springboot中使用Mybatis Generator的两种方式

    介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql. ...

  6. springboot中使用mybatis之mapper

    Spring Boot中使用MyBatis传参方式:使用@Param@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})& ...

  7. SpringBoot 中 使用Mybatis时 如果后端数据库为 Oracle注意事项

    报错信息如下: Could not set parameters for mapping: ParameterMapping{property='age', mode=IN, javaType=cla ...

  8. spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架

    前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...

  9. SpringBoot添加对Mybatis的支持

    1.修改maven配置文件pom.xml,添加对mybatis的支持: <dependency> <groupId>org.mybatis.spring.boot</gr ...

随机推荐

  1. FastReport.net 使用 WebForm 实现打印 最简单版

    1.安装demo 2.设计模版 设计器 -->report-->添加数据源-->添加sql查询->起名字(车信息)下一步-->填写sql语句(select top 1 * ...

  2. Codeforces 500C New Year Book Reading

    C. New Year Book Reading time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  3. Comet OJ - Contest #12

    B 整个表格其实是一些联通块,取反操作不能跨连通块.所以直接统计一下每个连通块内数字不对的个数是不是偶数即可 #include<iostream> #include<cstring& ...

  4. CTU Open 2018 Lighting /// 组合数递推 二进制

    题目大意: 给定n k 给定一个数的二进制位a[] 求这个数加上 另一个二进制位<=n的数b 后 能得到多少个不同的 二进制位有k个1 的数 样例 input10 51000100111 out ...

  5. android SharedPreferences 存储文件

  6. 【记录】jquery动态控制div隐藏或者显示

    1.jQuery判断一个元素当前状态是显示还是隐藏 $("#id").is(':visible'); //true为显示,false为隐藏 $("#id").i ...

  7. linux100day(day8)--shell监控脚本练习

    这是一个大型的监控脚本,方便于查看硬盘,网络,负载,内核版本等系统信息. 本脚本来自于github的atarallo,我对脚本做出了改编和一些注释,尽量让新手也能理解,这个脚本逻辑清楚简单,适合用于练 ...

  8. error: Error trying to parse settings: Unexpected trailing characters in Packages\User\Preferences.sublime-settings:9:2 reloading settings Packages/User/Preferences.sublime-settings

    error: Error trying to parse settings: Unexpected trailing characters in Packages\User\Preferences.s ...

  9. mysql 获取任意一个月的所有天数。

    SELECT ADDDATE(y.first, x.d - 1) as dFROM(SELECT 1 AS d UNION ALLSELECT 2 UNION ALLSELECT 3 UNION AL ...

  10. Mac系统下安装Homebrew后无法使用brew命令

    打开终端输入 brew提示:command not found 解决方法 输入命令: sudo vim .bash_profile 然后输入以下代码: export PATH=/usr/local/b ...