美文网首页JAVA技术栈JavaJava后台
四、Mybatis 执行流程全解析

四、Mybatis 执行流程全解析

作者: 一角钱技术 | 来源:发表于2019-07-13 22:49 被阅读808次

    知识点:
    执行流程解析
    Mybatis 插件开发

    一、执行流程解析

    1. 配置文件解析 configuration

    理解解析流程之前先回顾一下mybatis中配置文件的结构:

    mybatis-config.xml

    <configuration>
      <properties/>
      <settting/>
      <typeHandlers/>
      <..../>
      <mappers/>
    </configuration>
    

    mybatis-mapper.xml

    <mapper >
      <cache/>
      <resultMap/>
      <select/> 
      <update/> 
      <delete/> 
      <insert/> 
    </mapper>
    

    配置文件的解析流程即是将上述XML描述元素转换成对应的Java对象过程,其最终转换对象及其关系如下图:


    配置元素解析构建器

    >org.apache.ibatis.builder.xml.XMLConfigBuilder
     >org.apache.ibatis.builder.xml.XMLMapperBuilder
      >org.apache.ibatis.builder.xml.XMLStatementBuilder
       >org.apache.ibatis.builder.SqlSourceBuilder
        >org.apache.ibatis.scripting.xmltags.XMLScriptBuilder
     >org.apache.ibatis.builder.annotation.MapperAnnotationBuilder
    

    sql statement 构建流程源码

    >org.apache.ibatis.session.SqlSessionFactoryBuilder#build()
    //1.Config.xml 文件解析
    >org.apache.ibatis.builder.xml.XMLConfigBuilder#parse
     >org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration
      >org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement
    //2.Mapper.xml 文件解析
    >org.apache.ibatis.builder.xml.XMLMapperBuilder#parse 
     >org.apache.ibatis.builder.xml.XMLMapperBuilder#configurationElement
      >org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext(java.util.List<org.apache.ibatis.parsing.XNode>)
    //3.Statemen sql块解析
    >org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode
     >org.apache.ibatis.builder.MapperBuilderAssistant#addMappedStatement
    // 4.动态SQL脚本解析
    >org.apache.ibatis.scripting.xmltags.XMLLanguageDriver#createSqlSource()
    >org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseScriptNode()
    >org.apache.ibatis.scripting.xmltags.XMLScriptBuilder#parseDynamicTags()   
    

    2. 会话创建SqlSession

    首先我们还是先来了解一下会话对像的组成结构如下图:


    会话构建源码解析

    >org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSession(boolean)
     >org.apache.ibatis.session.defaults.DefaultSqlSessionFactory#openSessionFromDataSource
      >org.apache.ibatis.transaction.TransactionFactory#newTransaction
      >org.apache.ibatis.session.Configuration#newExecutor
       >org.apache.ibatis.executor.SimpleExecutor
       >org.apache.ibatis.executor.CachingExecutor
         //执行器插件包装
       >org.apache.ibatis.plugin.InterceptorChain#pluginAll(executor)
      >org.apache.ibatis.session.defaults.DefaultSqlSession#DefaultSqlSession() 
    

    3. 方法执行 StatementHandler

    StatementHandler 源码解析

    >org.apache.ibatis.session.defaults.DefaultSqlSession#selectList()
     >org.apache.ibatis.executor.CachingExecutor#query()
      >org.apache.ibatis.executor.BaseExecutor#query()
       >org.apache.ibatis.executor.BaseExecutor#queryFromDatabase
    >org.apache.ibatis.session.Configuration#newStatementHandler
    org.apache.ibatis.executor.statement.BaseStatementHandler#BaseStatementHandler
    org.apache.ibatis.session.Configuration#newParameterHandler
    org.apache.ibatis.plugin.InterceptorChain#pluginAll(parameterHandler)
    org.apache.ibatis.session.Configuration#newResultSetHandler
    org.apache.ibatis.plugin.InterceptorChain#pluginAll(resultSetHandler)
    >org.apache.ibatis.plugin.InterceptorChain#pluginAll(statementHandler)
    >org.apache.ibatis.executor.BaseExecutor#getConnection
    >org.apache.ibatis.executor.statement.PreparedStatementHandler#instantiateStatement
    >org.apache.ibatis.executor.statement.PreparedStatementHandler#parameterize
    >org.apache.ibatis.scripting.defaults.DefaultParameterHandler#setParameters
    org.apache.ibatis.type.BaseTypeHandler#setParameter
    org.apache.ibatis.type.UnknownTypeHandler#setNonNullParameter
    org.apache.ibatis.type.IntegerTypeHandler#setNonNullParameter
    

    二、myBatis插件开发

    插件的四大扩展点

    1. Executor
    2. StatementHandler
    3. ParameterHandler
    4. ResultSetHandler

    分页插件实现:
    用户在接口中声明Page 对像实现后,由插件实现自动分页。使用示例如下:

    public class Page implements java.io.Serializable {
       private int szie; // 每页大
       private int number; // 当前页码
    }
    

    page参数声明

    @Select("select * from user")
    List<User> selectByPage(String name, Page page);
    

    客户端调用

    mapper.selectByPage("小明", new Page(3, 2))
    
    select * from user  limit 10,20
    

    实现目标分解

    1. 修改 修改SQL 并添加 limit 语句
    2. 判断方法参数中是否有Page对象
    3. 取出Page对象 生成limit 语句
    4. 上述操作必须在PreparedStatement 对像生成前完成

    完整代码如下:

    package com.niuh.mybatis.dao;
    
    import com.sun.deploy.util.ReflectionUtil;
    import org.apache.ibatis.executor.parameter.ParameterHandler;
    import org.apache.ibatis.executor.statement.BaseStatementHandler;
    import org.apache.ibatis.executor.statement.StatementHandler;
    import org.apache.ibatis.mapping.BoundSql;
    import org.apache.ibatis.plugin.Interceptor;
    import org.apache.ibatis.plugin.Invocation;
    import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.Map;
    import java.util.Optional;
    import java.util.Properties;
    /**
     * @author: hejianhui
     * @create: 2019-07-13 10:48
     * @see PagePlugin
     * @since JDK1.8
     */
    public class PagePlugin implements Interceptor {
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            return null;
        }
    
        @Override
        public Object plugin(Object target) {
            if (target instanceof StatementHandler) {
                return Proxy.newProxyInstance(PagePlugin.class.getClassLoader(),
                        new Class[]{StatementHandler.class},
                        new PageHandler((StatementHandler) target));
            }
            return target;
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
    
    
        private class PageHandler implements InvocationHandler {
            StatementHandler handler;
    
            public PageHandler(StatementHandler handler) {
                this.handler = handler;
            }
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equalsIgnoreCase("prepare")) {
                    setParametersProxy();
                }
                return method.invoke(handler, args);
            }
    
            private void setParametersProxy() {
                ;
                if (handler.getBoundSql().getParameterObject() instanceof Map) {
                    ((Map) handler.getBoundSql().getParameterObject()).values().stream()
                            .filter(a -> a instanceof Page)
                            .findFirst()
                            .ifPresent(
                                    page -> {
                                        appendPageSql((Page) page);
                                    }
                            );
                }
            }
    
            private void appendPageSql(Page page) {
                try {
                    BoundSql sql = handler.getBoundSql();
                    sql.getSql();
                    String limit = String.format(" limit %s,%s", page.getBegin(), page.getSzie());
                    setFileValue("sql", sql, sql.getSql() + limit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    
    
        private Object getFileValue(String fileName, Object target) throws NoSuchFieldException, IllegalAccessException {
            Field sqlField = target.getClass().getDeclaredField(fileName);
            sqlField.setAccessible(true);
            return sqlField.get(target);
        }
    
        private Object setFileValue(String fileName, Object target, Object value) throws NoSuchFieldException, IllegalAccessException {
            Field sqlField = target.getClass().getDeclaredField(fileName);
            sqlField.setAccessible(true);
            sqlField.set(target, value);
            return sqlField.get(target);
        }
    }
    

    相关文章

      网友评论

        本文标题:四、Mybatis 执行流程全解析

        本文链接:https://www.haomeiwen.com/subject/oervkctx.html