springboot中的mybatis是如果使用pagehelper的
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的的更多相关文章
- springboot中使用mybatis的分页插件pageHelper
首先在pom.xml中配置 <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot ...
- SpringBoot中关于Mybatis使用的三个问题
SpringBoot中关于Mybatis使用的三个问题 转载请注明源地址:http://www.cnblogs.com/funnyzpc/p/8495453.html 原本是要讲讲PostgreSQL ...
- springboot中使用mybatis显示执行sql
springboot 中使用mybatis显示执行sql的配置,在properties中添加如下 logging.你的包名=debug 2018-11-27 16:35:43.044 [DubboSe ...
- 在springboot中集成mybatis开发
在springboot中利用mybatis框架进行开发需要集成mybatis才能进行开发,那么如何在springboot中集成mybatis呢?按照以下几个步骤就可以实现springboot集成myb ...
- 在springboot中使用Mybatis Generator的两种方式
介绍 Mybatis Generator(MBG)是Mybatis的一个代码生成工具.MBG解决了对数据库操作有最大影响的一些CRUD操作,很大程度上提升开发效率.如果需要联合查询仍然需要手写sql. ...
- springboot中使用mybatis之mapper
Spring Boot中使用MyBatis传参方式:使用@Param@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})& ...
- SpringBoot 中 使用Mybatis时 如果后端数据库为 Oracle注意事项
报错信息如下: Could not set parameters for mapping: ParameterMapping{property='age', mode=IN, javaType=cla ...
- spring-boot+mybatis开发实战:如何在spring-boot中使用myabtis持久层框架
前言: 本项目基于maven构建,使用mybatis-spring-boot作为spring-boot项目的持久层框架 spring-boot中使用mybatis持久层框架与原spring项目使用方式 ...
- SpringBoot添加对Mybatis的支持
1.修改maven配置文件pom.xml,添加对mybatis的支持: <dependency> <groupId>org.mybatis.spring.boot</gr ...
随机推荐
- v8引擎的优化
1.编译优化 V8采用JIT即使编译技术. 例如JAVA是先编译成字节码,再由JVM编译成机器码,V8则没有中间的字节码,直接由源码生成语法树,然后编译成机器码. 2.隐藏类 当定义一个构造函数,使用 ...
- 修改el-input
无论是input框,还是select, 都是对 el-input 进行修改: .houseRegisterCompany .el-input{ width: 130px; }
- C#的扩展方法学习
一,什么是扩展方法? 1,扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 2,扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用 ...
- mySQL部分疑问和小结(orale)
2015/10/15 1.mysql语句: ALTER table scfz_xewp add BGR varchar(255) after KYR 2.创建触发器时: --/ CREATE D ...
- kubernetes容器集群管理创建node节点kubeconfig文件
1.创建TLS Bootstrapping Token 2.创建kubelet kubeconfig 3.创建kube-proxy kubeconfig 安装和设置kubectl [root@mast ...
- 从前端角度出发有哪些注意事项有利于SEO?
1.提高页面加载速度. 能用css解决的不用背景图片,背景图片也尽量压缩大小,可以几个icons放在一个图片上,使用background-position找到需要的图片位置.可以减少HTTP请求数,提 ...
- 使用egg.js和egg-sequelize连接mysql
1.通过 egg-init 初始化一个项目: egg-init --type=simple --dir=sequelize-projectcd sequelize-projectnpm i 2.安装并 ...
- postgresql中rank() over, dense_rank(), row_number() 的用法和区别
- Hibernate Session 4种对象状态
站在持久化的角度.Hibernate把对象分为4中状态. 临时状态. 持久化状态.游离状态.删除状态. 1:Save()方法: //这个是验证:1:save方法使临时对象------>变成持久化 ...
- JRE和JVM的区别
JRE和JVM的区别 JRE(JavaRuntimeEnvironment,Java运行环境),也就是Java平台.所有的Java程序都要在JRE下才能运行.JDK的工具也是Java程序, ...