pageHelper分页插件原理
一: 使用篇
pom中引入
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.0</version>
</dependency>
mybatis-config.xml 加入插件
<!--分页插件的注册 以下property参数可以去官网找解释-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 4.0.0以后版本可以不设置该参数 ,可以自动识别
<property name="dialect" value="mysql"/> -->
<!-- 该参数默认为false -->
<!-- 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 -->
<!-- 和startPage中的pageNum效果一样-->
<property name="offsetAsPageNum" value="true"/>
<!-- 该参数默认为false -->
<!-- 设置为true时,使用RowBounds分页会进行count查询 -->
<property name="rowBoundsWithCount" value="true"/>
<!-- 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果 -->
<!-- (相当于没有执行分页查询,但是返回结果仍然是Page类型)-->
<property name="pageSizeZero" value="true"/>
<!-- 3.3.0版本可用 - 分页参数合理化,默认false禁用 -->
<!-- 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页 -->
<!-- 禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据 -->
<property name="reasonable" value="true"/>
<!-- 3.5.0版本可用 - 为了支持startPage(Object params)方法 -->
<!-- 增加了一个`params`参数来配置参数映射,用于从Map或ServletRequest中取值 -->
<!-- 可以配置pageNum,pageSize,count,pageSizeZero,reasonable,orderBy,不配置映射的用默认值 -->
<!-- 不理解该含义的前提下,不要随便复制该配置 -->
<property name="params" value="pageNum=start;pageSize=limit;"/>
<!-- 支持通过Mapper接口参数来传递分页参数 -->
<property name="supportMethodsArguments" value="true"/>
<!-- always总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
<property name="returnPageInfo" value="check"/>
</plugin>
</plugins>
业务代码中
/**
* 查询员工数据 分页
*
* @param pn
* @param model
* @return
* @RequestMapping("/emps")
*/
public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) {
PageHelper.startPage(pn, 10); // pn是页码 10是每页的条数
List<Employee> emps = employeeService.getAll();
PageInfo page = new PageInfo(emps, 10);
//包装查出来的结果,只需要将pageInfo交给页面,封装了详细的分页信息
//包括查询出来的数据
model.addAttribute("pageInfo", page);
return "list";
}
二:原理源码分析
这里只分析pageHelper涉及到的mybatis源码及pageHelper是怎么和mybatis整合的。
1.mybatis查询的时候是需要executor执行器的,它一共有3种实现BatchExecutor,ReuseExecutor,SimpleExecutor,至于3者的区别自己查下。executor这个执行器是在DefaultSqlSession.openSession时候获得的。
2.mybatis为插件预留了Interceptor接口,所有扩展的插件都需要实现这个接口。这个接口一共有3个方法。
intercept 执行插件的方法
plugin 生成Interceptor的代理对象
setProperties 设置属性
3.分页插件pageHelper实现mybatis的预留Interceptor接口,重写上面的3个方法。
4.pageHelper定义拦截方法,mybatis只有4个接口是可以装入插件的Executor是其中的一个,其余的去查下。
executor的query被调用时就会被拦截到。
@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
DefaultSqlSessionFactory.java
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
源码流程分析///
//创建执行器
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
Configuration.java
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
源码流程分析///
// 1.根据指定的执行器种类创建不通的执行器的实现,默认这个种类是null,也就是默认的实现是SimpleExecutor
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
// 2. 对于创建的执行器对象进行包装,也就是二级缓存CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
// 3. 关键的一步,把执行器放入interceptorChain 责任链
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
InterceptorChain.java
源码流程分析///
// 这个interceptors的集合放入的就是在mybatis-config.xml中放入的插件,也就是pageHelper。如果有多个插件的话都放入这个集合中,所以调用的时候也就是层层调用,层层代理。至于这个插件是在什么时候放入的这个集合,是在创建DefaultSqlSessionFactory时候解析mybatis-config.xml时候放入的。
private final List<Interceptor> interceptors = new ArrayList<>();
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
// 这里该调用到PageHelper.plugin()中
target = interceptor.plugin(target);
}
return target;
}
PageInterceptor.java 也就是mybatis的预留插件接口的plugin是用来创建代理对象的。
@Override
public Object plugin(Object target) {
源码流程分析///
// 走入到Plugin.wrap()中去创建执行器的代理对象 这个plugin是mybatis的
return Plugin.wrap(target, this);
}
Plugin.java
public static Object wrap(Object target, Interceptor interceptor) {
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
Class<?> type = target.getClass();
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
if (interfaces.length > 0) {
源码流程分析///
// 创建executor的代理对象。Plugin类实现了InvocationHandler接口所以这个类拥有invoke方法
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
源码流程分析///
// 代理对象被调用的时候是要先执行代理对象的invoke的。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
if (methods != null && methods.contains(method)) {
// 就是interceptor接口的intercept()。也就是调用到PageHelper的intercept()中去。
return interceptor.intercept(new Invocation(target, method, args));
}
// 代理对象的方法执行完了,调用原来executor的实现类的方法
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
PageInterceptor.java
源码流程分析///
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
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;
//由于逻辑关系,只会进入一次
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;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//反射获取动态参数
Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
//创建 count 查询的缓存 key
CacheKey countKey = executor.createCacheKey(ms, parameter, RowBounds.DEFAULT, boundSql);
countKey.update("_Count");
MappedStatement countMs = msCountMap.get(countKey);
if (countMs == null) {
//根据当前的 ms 创建一个返回值为 Long 类型的 ms
countMs = MSUtils.newCountMappedStatement(ms);
msCountMap.put(countKey, countMs);
}
//调用方言获取 count sql
String countSql = dialect.getCountSql(ms, boundSql, parameter, rowBounds, countKey);
BoundSql countBoundSql = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter);
//当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中
for (String key : additionalParameters.keySet()) {
countBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//执行 count 查询
Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
Long count = (Long) ((List) countResultList).get(0);
//处理查询总数
//返回 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 这里就是根据具体的数据库去拼接不通的分页查询sql。mysql拼接limit oracle拼接row。这里用到了在业务最外PageHelper.startPage(pn, 10);设置的这个值,设置的时候是放入到thraadLocal中去了,获取的时候从threadLocal中去获取。
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
// 把分页的sql拼接到业务sql上
BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), 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();
}
}
三:总结
1.pageHelper的原理是利用mybatis的预留Interceptor接口,插件去实现这个接口。把实现了Interceptor的实现类放入到 List interceptors中,最终调用到插件里的plugin()中。这个接口负责生成对于Executor的JDK代理对象。Plugin.wrap()是最终产生代理对象。代理对象被调用进入到invoke()中,这里再调用插件的intercept()进行分页参数的拼接。
简述就是把executor进行代理增强,通过产生的代理对象调用到插件的intercept()中,然后根据数据库的方言生成应分页sql,分页sql拼接到业务sql上,然后再调用到真实的SimpleExecutor中去继续执行sql。