spring-boot-2.0.3源码篇 - pageHelper分页,绝对有值得你看的地方
开心一刻
说实话,作为一个宅男,每次被淘宝上的雄性店主追着喊亲,亲,亲,这感觉真是恶心透顶,好像被强吻一样
更烦的是我每次为了省钱,还得用个女号,跟那些店主说:“哥哥包邮嘛么叽”,“哥哥再便宜点呗,我钱不够了嘛,5555555”
问题背景
用过 pageHelper 的都知道(没用过的赶紧去百度下),实现分页非常简单,service 实现层调用 dao(mapper) 层之前进行 page 设置,mapper.xml 中不处理分页,这样就够了,就能实现分页了,具体如下
UserServiceImpl.java
@Override public PageInfo listUser(int pageNum, int pageSize) {PageHelper.startPage(pageNum, pageSize); List<User> users = userMapper.listUser(); PageInfo pageInfo = new PageInfo(users); return pageInfo; }
UserMapper.xml
<select id="listUser" resultType="User">
SELECT
id,username,password,salt,state,description
FROM
tbl_user
</select>
哎我去,这样就实现分页了? 老牛皮了,这是为什么,这是怎么做到的? 凡事有果必有因,我们一起来看看这个因到底是什么
JDK 的动态代理
在进入正题之前了,我们先来做下准备,如果对动态代理很熟悉的直接略过往下看,建议还是看看,权且当做热身
我们来看看 JDK 下的动态代理的具体实现:proxyDemo,运行 ProxyTest 的 main 方法,结果如下
可以看到我们对 张三 进行了增强处理,追加了后缀:_proxy
更多动态代理信息请看:设计模式之代理,手动实现动态代理,揭秘原理实现
Mybatis sql 执行流程
当我们对 JDK 的动态代理有了一个基本认识之后了,我们再完成个一公里的慢跑:熟悉 Mybatis 的 sql 执行流程。流程图懒得画了,有人处理的很优秀了,我引用下
图片摘至《深入理解 mybatis 原理》 MyBatis 的架构设计以及实例分析
分页源码解析
业务代码中的 PageHelper
我们先来跟一跟业务代码中的 PageHelper 的代码
PageHelper.startPage(pageNum, pageSize);
看它到底做了什么,如下图
我们发现,进行了 Page 的相关设置后,将 Page 放到了当前线程中,没做其他的什么,那么分页肯定不是在这做的。
PageHelper 自动配置
关于怎么找自动配置类,可参考:spring-boot-2.0.3 启动源码篇一 - SpringApplication 构造方法,此时我们找到了 PageHelperAutoConfiguration,源代码如下
/** * 自定注入分页插件 * * @author liuzh */ @Configuration @ConditionalOnBean(SqlSessionFactory.class) @EnableConfigurationProperties(PageHelperProperties.class) @AutoConfigureAfter(MybatisAutoConfiguration.class) public class PageHelperAutoConfiguration {@Autowired </span><span style="color: rgba(0, 0, 255, 1)">private</span> List<SqlSessionFactory><span style="color: rgba(0, 0, 0, 1)"> sqlSessionFactoryList; @Autowired </span><span style="color: rgba(0, 0, 255, 1)">private</span><span style="color: rgba(0, 0, 0, 1)"> PageHelperProperties properties; </span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)"> * 接受分页插件额外的属性 * * </span><span style="color: rgba(128, 128, 128, 1)">@return</span> <span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)"> @Bean @ConfigurationProperties(prefix </span>=<span style="color: rgba(0, 0, 0, 1)"> PageHelperProperties.PAGEHELPER_PREFIX) </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Properties pageHelperProperties() { </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Properties(); } @PostConstruct </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> addPageInterceptor() { PageInterceptor interceptor </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> PageInterceptor(); Properties properties </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> Properties(); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">先把一般方式配置的属性放进去</span>
properties.putAll(pageHelperProperties());
//在把特殊配置放进去,由于 close-conn 利用上面方式时,属性名就是 close-conn 而不是 closeConn,所以需要额外的一步
properties.putAll(this.properties.getProperties());
interceptor.setProperties(properties);
for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) {
// 将 PageInterceptor 实例添加到了 Configuration 实例的 interceptor 链中
sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
}
}}
在 PageHelperAutoConfiguration 的构造方法执行完之后,会执行 addPageInterceptor 方法,完成配置属性的注入,并将 PageInterceptor 实例添加到了 Configuration 实例的 interceptorChain 中。
从 Mybatis 的 SQL 执行流程图中可以 Mybatis 的四大对象 Executor、ParameterHandler、ResultSetHandler、StatementHandler,由他们一起合作完成 SQL 的执行,那么这四大对象是由谁创建的呢?没错,就是 Mybatis 的配置中心:Configuration,创建源代码如下:
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) { ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql); parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler); return parameterHandler; }public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}public Executor newExecutor(Transaction transaction) {
return newExecutor(transaction, defaultExecutorType);
}public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
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);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
可以看到四大对象创建的最后,都会调用 interceptorChain.pluginAll,我们来看看 pluginAll 方法做了什么
其中 Plugin 的 wrap 方法要注意下
public static Object wrap(Object target, Interceptor interceptor) { // 获取 PageInterceptor 的 Intercepts 注解中 @Signature 的 method,存放到 Plugin 的 signatureMap 中 Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor); Class<?> type = target.getClass(); // 获取目标对象实现的全部接口;四大对象是接口,都有默认的子类实现 // JDK 的动态代理只支持接口 Class<?>[] interfaces = getAllInterfaces(type, signatureMap); if (interfaces.length > 0) { return Proxy.newProxyInstance(type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap)); } return target; }
pluginAll 其实就是给四大对象创建代理,一个 Interceptor 就会创建一层代理,而我们的 PageInterceptor 只是其中一层代理;我们接着往下看,Plugin 继承了 InvocationHandler,相当于上述:JDK 的动态代理示例中的 MyInvocationHandler,那么它的 invoke 方法肯定会被调用
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { // 获取 PageInterceptor 的 Intercepts 注解中 @Signature 的 method Set<Method> methods = signatureMap.get(method.getDeclaringClass()); // 当 methods 包含目标方法时,调用 PageInterceptor 的 intercept 方法完成 SQL 的分页处理 if (methods != null && methods.contains(method)) { return interceptor.intercept(new Invocation(target, method, args)); } return method.invoke(target, args); } catch (Exception e) { throw ExceptionUtil.unwrapThrowable(e); } }
拦截器:PageInterceptor
上述我们讲到了,当匹配时会进入到 PageInterceptor 的 intercept 方法中,在解读 intercept 方法之前,我们先来看看 PageInterceptor 类上的注解
@Intercepts( { // 相当于对 Executor 的 query 方法做拦截处理 @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}),} )
这就标明了 PageInterceptor 拦截的是 Executor 的 query 方法;还记上述 wrap 方法的
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
吗?读取的就是 @Intercepts 下 @Signature 中的内容。我们接着看 intercept
@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; //调用方法判断是否需要进行分页,如果不需要,直接返回结果 // 此处会从当前线程取 Page 信息,还记得什么时候在哪将 Page 信息放进当前线程的吗? if (!dialect.skip(ms, parameter, rowBounds)) { //反射获取动态参数 String msId = ms.getId(); Configuration configuration = ms.getConfiguration(); Map<String, Object> additionalParameters = (Map<String, Object>)additionalParametersField.get(boundSql); //判断是否需要进行 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 信息,根据 Page 信息来断定是否需要分页;而 Page 信息就是从我们的业务代码中存放到当前线程的。PageHelper 的作者已经将 intercept 方法中的注释写的非常清楚了,相信大家都能看懂。
到了此刻,相信大家都清楚了,还不清楚的静下心来好好捋一捋。
总结
1、PageHelper 属于 Mybatis 插件拓展,也可称拦截器拓展,是基于 Mybatis 的 Interceptor 实现;
2、Page 信息是在我们的业务代码中放到当前线程的,作为后续是否需要分页的条件;
3、Mybatis 创建 mapper 代理的过程(详情请看:Mybatis 源码解析 - mapper 代理对象的生成)中,也会创建四大对象的代理 (有必要的话),而 PageInterceptor 对应的四大对象的代理会拦截 Executor 的 query 方法,将分页参数添加到目标 SQL 中;
4、不管我们是否需要分页,只要我们集成了 PageHelper,那么四大对象的代理实现中肯定包含了一层 PageHelper 的代理(可能是多层代理,包括其他第三方的 Mybatis 插件,或者我们自定义的 Mybatis 插件),如果当前线程中设置了 Page,那么就表示需要分页,PageHelper 就会读取当前线程中的 Page 信息,将分页条件添加到目标 SQL 中(Mysql 是后面添加 LIMIT,而 Oracle 则不一样),那么此时发送到数据库的 SQL 是有分页条件的,也就完成了分页处理;
5、@Interceptors、@Signature 以及 Plugin 类,三者配合起来,完成了分页逻辑的植入,Mybatis 这么做便于拓展,使用起来更灵活,包容性更强;我们自定义插件的话,可以基于此,也可以抛弃这 3 个类,直接在 plugin 方法内部根据 target 实例的类型做相应的操作;个人推荐基于这 3 个来实现;
6、Mybatis 的 Interceptor 是基于 JDK 的动态代理,只能针对接口进行处理;另外,当我们进行 Mybatis 插件开发的时候,需要注意顺序问题,可能会与其他的 Mybatis 插件有冲突。