Mybatis源码探索篇,分析整体架构(先捋脉络,再扣细节)

Mybatis源码初探

上篇文章我们通过模拟Mybatis对sql进行来了简单的逻辑处理,大概知道了它是如何处理sql语句的,紧接着我们来聊一聊Mybatis的架构设计。

Mybatis的架构设计

XML 配置文件中包含了对 MyBatis 系统的核心设置,包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)(来自中文官网介绍)

xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

那么此时我们肯定需要对xml的配置文件进行解析操作(具体解析方式可以用dom4j)

  1. 解析配置文件
  2. 获取到对应的mapper接口
  3. 获取到StatementHandler
  4. 执行sql语句
  5. 进行结果集的映射(ResultSetHandler)

其它关于Mybatis的书籍对于Mybatis的核心架构写的比较复杂,我写的这个对其做了简化处理,大致认为Mybatis的核心处理架构就是以下几个步骤:

我们可以从下述代码中debug来看代码流程走向

java 复制代码
public class MyTest {

    SqlSessionFactory sqlSessionFactory = null;

    @Before
    public void init(){
      // 根据全局配置文件创建出SqlSessionFactory
      // SqlSessionFactory:负责创建SqlSession对象的工厂
      // SqlSession:表示跟数据库建议的一次会话
      String resource = "mybatis-config.xml";
      InputStream inputStream = null;
      try {
        inputStream = Resources.getResourceAsStream(resource);
      } catch (IOException e) {
        e.printStackTrace();
      }
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void test01() {

        // 获取数据库的会话,创建出数据库连接的会话对象(事务工厂,事务对象,执行器,如果有插件的话会进行插件的解析)
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Emp empByEmpno = null;
        try {
            // 获取要调用的接口类,创建出对应的mapper的动态代理对象(mapperRegistry.knownMapper)
            EmpDao mapper = sqlSession.getMapper(EmpDao.class);
            // 调用方法开始执行
            empByEmpno = mapper.findEmpByEmpno(7369);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        System.out.println(empByEmpno);
    }

这里的xml文件转换为inputStream的过程不需要去读(如有需要自行阅读)

通过SqlSessionFactoryBuilder来构建SqlSession对象,构建流程的细节如下:

初始化了全局的configuration对象

开始配置文件的解析工作

首先解析了根标签 /configuration,然后可以解析根标签下的子标签

java 复制代码
private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      // 解析properties
      propertiesElement(root.evalNode("properties"));
      // 解析settings
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      // 设置vfsImpl字段
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      // 解析类型别名
      typeAliasesElement(root.evalNode("typeAliases"));
      // 解析插件
      pluginElement(root.evalNode("plugins"));
      // 对象工厂
      objectFactoryElement(root.evalNode("objectFactory"));
      // 对象包装工厂
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      // 反射工厂
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);//设置具体的属性到configuration对象
      // read it after objectFactory and objectWrapperFactory issue #631
      // 环境
      environmentsElement(root.evalNode("environments"));
      // databaseIdProvider
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      // 类型处理器
      typeHandlerElement(root.evalNode("typeHandlers"));
      // 映射器
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

这里包含了很多标签的解析工作,但是我们只看最重要的mappers标签的解析工作怎么做的(其余标签的解析有兴趣可自行查看)

因为mappers的子标签 mapper的映射形式有好几种 resource(类路径)、url(url绝对路径)、class(java类名)、package(自动扫描包下所有映射器),所以源码这里做了一些判断,下述内容来自于Mybatis中文官网:

xml 复制代码
<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>

<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>

<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>

<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

源码处对mappers标签的详细解析工作

java 复制代码
private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      // 处理mapper子节点
      for (XNode child : parent.getChildren()) {
        // package子节点
        if ("package".equals(child.getName())) {
          // 自动扫描包下所有映射器
          String mapperPackage = child.getStringAttribute("name");
          // 扫描指定的包,并向mapperRegistry注册mapper接口
          configuration.addMappers(mapperPackage);
        } else {
          // 获取mapper节点的resource、url、class属性,三个属性互斥
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          // 如果mapper节点指定了resource或者url属性,则创建XmlMapperBuilder对象,并通过该对象解析resource或者url属性指定的mapper配置文件
          if (resource != null && url == null && mapperClass == null) {
            // 使用类路径
            ErrorContext.instance().resource(resource);
            try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
              // 创建XMLMapperBuilder对象,解析映射配置文件
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } else if (resource == null && url != null && mapperClass == null) {
            // 使用绝对url路径
            ErrorContext.instance().resource(url);
            try(InputStream inputStream = Resources.getUrlAsStream(url)){
              // 创建XMLMapperBuilder对象,解析映射配置文件
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } else if (resource == null && url == null && mapperClass != null) {
            // 如果mapper节点指定了class属性,则向MapperRegistry注册该mapper接口
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            // 直接把这个映射加入配置
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

毫无意外的,把 最后解析的数据都放到了全局的configuration这个对象中。 这里已经可以取到方法的全限定名了

最终返回了SqlSessionFactory,接下来开始获取数据库的会话(SqlSession对象)

在创建SqlSession对象时,数据库此时还没有建立连接,使用的是默认执行器(SimpleExecutor)

此时开始通过动态代理的形式创建出对应mapper的动态代理对象

java 复制代码
// 返回代理类
  @SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 查找指定type对应MapperProxyFactory对象
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    // 如果mapperProxyFactory为空,则抛出异常
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
      // 创建实现了type接口的代理对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

这个时候已经获取到了代理对象,此时调用具体的接口方法就ok了,调用invoke方法

java 复制代码
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      // 如果目标方法继承自Object,则直接调用目标方法
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else {
        // 根据被调用接口方法的method对象,从缓存中获取MapperMethodInvoker对象,如果没有则创建一个并放入缓存,然后调用invoke
        return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
  }

根据sqlCommand指令来判断执行什么sql语句(这里是SELECT)

java 复制代码
public Object execute(SqlSession sqlSession, Object[] args) {
    Object result;
    // 根据SQL语句的类型调用SqlSession对应的方法
    switch (command.getType()) {
      case INSERT: {
        // 使用ParamNameResolver处理args数组,将用户传入的实参与指定参数名称关联起来
        Object param = method.convertArgsToSqlCommandParam(args);
        // 调用sqlSession.insert方法,rowCountResult方法会根据method字段中记录的方法的返回值类型对结果进行转换
        result = rowCountResult(sqlSession.insert(command.getName(), param));
        break;
      }
      case UPDATE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.update(command.getName(), param));
        break;
      }
      case DELETE: {
        Object param = method.convertArgsToSqlCommandParam(args);
        result = rowCountResult(sqlSession.delete(command.getName(), param));
        break;
      }
      case SELECT:
        // 处理返回值为void是ResultSet通过ResultHandler处理的方法
        if (method.returnsVoid() && method.hasResultHandler()) {
          // 如果有结果处理器
          executeWithResultHandler(sqlSession, args);
          result = null;
          // 处理返回值为集合和数组的方法
        } else if (method.returnsMany()) {
          // 如果结果有多条记录
          result = executeForMany(sqlSession, args);
          // 处理返回值为map的方法
        } else if (method.returnsMap()) {
          // 如果结果是map
          result = executeForMap(sqlSession, args);
          // 处理返回值为cursor的方法
        } else if (method.returnsCursor()) {
          result = executeForCursor(sqlSession, args);
        } else {
          // 处理返回值为单一对象的方法
          Object param = method.convertArgsToSqlCommandParam(args);
          result = sqlSession.selectOne(command.getName(), param);
          if (method.returnsOptional()
              && (result == null || !method.getReturnType().equals(result.getClass()))) {
            result = Optional.ofNullable(result);
          }
        }
        break;
      case FLUSH:
        result = sqlSession.flushStatements();
        break;
      default:
        throw new BindingException("Unknown execution method for: " + command.getName());
    }
    if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
      throw new BindingException("Mapper method '" + command.getName()
          + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
    }
    return result;
  }

然后接着我们就可以查看到封装好一些参数的statement对象

并通过执行器去执行sql语句,boundSql获取到sql语句

java 复制代码
@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
    // 获取BoundSql对象
    BoundSql boundSql = ms.getBoundSql(parameterObject);
    // 创建CacheKey对象
    CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
    return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

下面判断是否开启二级缓存来走sql查询

java 复制代码
@Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    // 获取查询语句所在命名空间对应的二级缓存
    Cache cache = ms.getCache();
    // 是否开启了二级缓存
    if (cache != null) {
      // 根据select节点的配置,决定是否需要清空二级缓存
      flushCacheIfRequired(ms);
      // 检测SQL节点的useCache配置以及是否使用了resultHandler配置
      if (ms.isUseCache() && resultHandler == null) {
        // 二级缓存不能保存输出类型的参数,如果查询操作调用了包含输出参数的存储过程,则报错
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        // 查询二级缓存
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          // 二级缓存没有相应的结果对,调用封装的Executor对象的query方法
          list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          // 将查询结果保存到TransactionalCache.entriesToAddOnCommit集合中
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    // 没有启动二级缓存,直接调用底层Executor执行数据库查询操作
    return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

queryFromDatabase方法,并且得到映射后的结果对象

java 复制代码
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    // 检测当前Executor是否已经关闭
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      // 非嵌套查询,并且select节点配置的flushCache属性为true时,才会清空一级缓存,flushCache配置项是影响一级缓存中结果对象存活时长的第一个方面
      clearLocalCache();
    }
    List<E> list;
    try {
      // 增加查询层数
      queryStack++;
      // 查询一级缓存
      list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
      if (list != null) {
        // 针对存储过程调用的处理,在一级缓存命中时,获取缓存中保存的输出类型参数,并设置到用户传入的实参对象中
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        // 调用doQuery方法完成数据库查询,并得到映射后的结果对象
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      // 当前查询完成,查询层数减少
      queryStack--;
    }
    if (queryStack == 0) {
      // 在最外层的查询结束时,所有嵌套查询也已经完成,相关缓存项也已经完全记载,所以在此处触发DeferredLoad加载一级缓存中记录的嵌套查询的结果对象
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      // 加载完成后,清空deferredLoads集合
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        // 根据LocalCacheScope配置决定是否清空一级缓存
        clearLocalCache();
      }
    }
    return list;
  }

这里得到了 StatementHandler对象

java 复制代码
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      // 获取配置对象
      Configuration configuration = ms.getConfiguration();
      // 创建StatementHandler对象,实际返回的是RoutingStatementHandler对象
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      // 完成Statement的创建和初始化
      stmt = prepareStatement(handler, ms.getStatementLog());
      // 调用query方法执行sql语句,并通过ResultSetHandler完成结果集的映射
      return handler.query(stmt, resultHandler);
    } finally {
      // 关闭Statement对象
      closeStatement(stmt);
    }
  }

在进行Statement的创建和初始化时,获取了Connection对象

java 复制代码
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    // 创建Statement对象
    stmt = handler.prepare(connection, transaction.getTimeout());
    // 处理占位符
    handler.parameterize(stmt);
    return stmt;
  }

通过ResultSetHandler对象对结果集做出处理并返回

java 复制代码
@Override
  public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
    PreparedStatement ps = (PreparedStatement) statement;
    ps.execute();
    return resultSetHandler.handleResultSets(ps);
  }

以上的内容大概就是Mybatis的架构流程的整体脉络,后续的mappers标签的解析、StatementHandler如何处理sql语句、执行器如何执行sql语句、ResultSetHandler如何进行结果集的映射请继续查看后续章节(先捋脉络,再扣细节)

相关推荐
杨哥带你写代码1 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
AskHarries1 小时前
读《show your work》的一点感悟
后端
A尘埃2 小时前
SpringBoot的数据访问
java·spring boot·后端
yang-23072 小时前
端口冲突的解决方案以及SpringBoot自动检测可用端口demo
java·spring boot·后端
Marst Code2 小时前
(Django)初步使用
后端·python·django
代码之光_19802 小时前
SpringBoot校园资料分享平台:设计与实现
java·spring boot·后端
编程老船长2 小时前
第26章 Java操作Mongodb实现数据持久化
数据库·后端·mongodb
IT果果日记2 小时前
DataX+Crontab实现多任务顺序定时同步
后端
小徐敲java4 小时前
通用mybatis-plus查询封装(QueryGenerator)
mybatis
姜学迁4 小时前
Rust-枚举
开发语言·后端·rust