本文共 9243 字,大约阅读时间需要 30 分钟。
说实话,作为一个宅男,每次被淘宝上的雄性店主追着喊“亲,亲,亲”,这感觉真的很恶心,仿佛被强吻一样。更让人烦的是为了省钱,我不得不用个女号跟那些店主沟通:“哥哥包邮吗?”“哥哥再便宜点呗,我钱不够了嘛,5555555。”这些日子真是充满了不堪的苦难。
用过PageHelper的都知道(没用过的赶紧去百度下),实现分页非常简单。服务实现层调用DAO层之前进行Page设置,Mapper.xml中不处理分页,这样就够了,就能实现分页了。以下是具体实现代码:
@Overridepublic PageInfo listUser(int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); Listusers = userMapper.listUser(); PageInfo pageInfo = new PageInfo(users); return pageInfo;}
哎我去,这样就实现分页了?这是什么意思?这是怎么做到的?凡事有果必有因,我们一起来看看这个因到底是什么。
在进入正题之前,我们先做下准备。如果对动态代理很熟悉,可以略过,但建议还是看看,权且当做热身。
我们来看看JDK下的动态代理的具体实现:
public class PageHelperAutoConfiguration { @Autowired private ListsqlSessionFactoryList; @Autowired private PageHelperProperties properties; @Bean @ConfigurationProperties(prefix = PageHelperProperties.PAGEHELPER_PREFIX) public Properties pageHelperProperties() { return new Properties(); } @PostConstruct public void addPageInterceptor() { PageInterceptor interceptor = new PageInterceptor(); Properties properties = new Properties(); properties.putAll(pageHelperProperties()); properties.putAll(this.properties.getProperties()); interceptor.setProperties(properties); for (SqlSessionFactory sqlSessionFactory : sqlSessionFactoryList) { sqlSessionFactory.getConfiguration().addInterceptor(interceptor); } }}
从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;}
pluginAll方法的实现如下:
public static Object wrap(Object target, Interceptor interceptor) { MapsignatureMap = getSignatureMap(interceptor); Class type = target.getClass(); Class [] interfaces = getAllInterfaces(type, signatureMap); if (interfaces.length > 0) { return Proxy.newProxyInstance( type.getClassLoader(), interfaces, new Plugin(target, interceptor, signatureMap) ); } return target;}
pluginAll其实就是给四大对象创建代理,而我们的PageInterceptor只是其中一层代理。我们接着往下看,Plugin继承了InvocationHandler,相当于上述:JDK的动态代理示例中的MyInvocationHandler,它的invoke方法肯定会被调用:
@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { Setmethods = signatureMap.get(method.getDeclaringClass()); 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); }}
在解读intercept方法之前,我们先来看看PageInterceptor类上的注解:
@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})})
这就标明了PageInterceptor拦截的是Executor的query方法;还记上述wrap方法的:
MapsignatureMap = getSignatureMap(interceptor);
吗?读取的就是@Intercepts下@Signature中的内容。我们接着看intercept方法:
@Overridepublic 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) { boundSql = ms.getBoundSql(parameter); cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql); } else { cacheKey = (CacheKey) args[4]; boundSql = (BoundSql) args[5]; } List resultList; if (!dialect.skip(ms, parameter, rowBounds)) { String msId = ms.getId(); Configuration configuration = ms.getConfiguration(); MapadditionalParameters = (Map ) additionalParametersField.get(boundSql); if (dialect.beforeCount(ms, parameter, rowBounds)) { String countMsId = msId + countSuffix; Long count; MappedStatement countMs = getExistedMappedStatement(configuration, countMsId); if (countMs != null) { count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler); } else { countMs = msCountMap.get(countMsId); if (countMs == null) { countMs = MSUtils.newCountMappedStatement(ms, countMsId); msCountMap.put(countMsId, countMs); } count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler); } if (!dialect.afterCount(count, parameter, rowBounds)) { return dialect.afterPage(new ArrayList(), parameter, rowBounds); } } if (dialect.beforePage(ms, parameter, rowBounds)) { parameter = dialect.processParameterObject(ms, parameter, boundSql, cacheKey); String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, cacheKey); 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, cacheKey, pageBoundSql); } else { resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql); } } else { 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代理的过程(详情请看:)中,也会创建四大对象的代理(有必要的话),而PageInterceptor对应的四大对象的代理会拦截Executor的query方法,将分页参数添加到目标SQL中;
4、不管我们是否需要分页,只要我们集成了PageHelper,那么四大对象的代理实现中肯定包含了一层PageHelper的代理(可能是多层代理,包括其他第三方的Mybatis插件,或者我们自定义的Mybatis插件),如果当前线程中设置了Page,那么就表示需要分页,PageHelper就会读取当前线程中的Page信息,将分页条件添加到目标SQL中(Mysql是后面添加LIMIT,而Oracle则不一样),那么此时发送到数据库的SQL是有分页条件的,也就完成了分页处理;
5、@Intercepts、@Signature以及Plugin类,三者配合起来,完成了分页逻辑的植入,Mybatis这么做便于拓展,使用起来更灵活,包容性更强;我们自定义插件的话,可以基于此,也可以抛弃这3个类,直接在plugin方法内部根据target实例的类型做相应的操作;个人推荐基于这3个来实现;
6、Mybatis的Interceptor是基于JDK的动态代理,只能针对接口进行处理;另外,当我们进行Mybatis插件开发的时候,需要注意顺序问题,可能会与其他的Mybatis插件有冲突。
转载地址:http://dilbz.baihongyu.com/