Mybatis源码分析


使用Mybatis框架执行数据库访问的CURD操作如下,通过这几行代码了解Mybatis运行时的整个流程:

@Test
public void test1() throws IOException {
    //读取并解析mybatis配置文件,创建SqlSessionFactory
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //创建SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //执行SQL
    List<User> users = sqlSession.selectList("edu.hzb.dao.UserDAO.selectList");
}

上面的代码主要分为三步:

  1. 读取并且解析Mybatis配置文件mybatis-config.xml,创建SqlSessionFactory(也就是Mybatis的初始化)
  2. 创建SqlSession对象
  3. 利用SqlSession对象执行Sql语句

Mybatis初始化

首先看第一步的代码:

//读取并解析mybatis配置文件,创建SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

先将mybatis-config.xml配置文件内容转换为字符流(Reader)或者字节流(InputStream)。然后根据流数据创建SqlSessionFactory。进入到build(inputStream)方法中。

public SqlSessionFactory build(InputStream inputStream) {
  return build(inputStream, null, null);
}

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      //environment和properties为空
      //XML文件解析器,内部封装了XPath,用于解析XML文件
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      //parser.parse()方法用于解析mybatis-config.xml文件,并且返回Configuration对象
      //build(parser.parse())方法根据Configuration对象创建SqlSessionFactory(实现类是		DefaultSqlSessionFactory)
      return build(parser.parse());
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        inputStream.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }
  1. XMLConfigBuilder对象用于解析XML文件,解析xml文件的方式常见有三种,包括DOM方式、SAX方式、XPath方式,这里采用的是XPath。

  2. parser.parse()方法用于解析mybatis-config.xml文件流,转为为Configuration对象

    Configuration对象是Mybatis中核心对象,主要包含一下两大功能:
    封装Mybatis配置信息:
    	1、mybatis-config.xml文件中的配置,比如常见的<setting/>、<environment/>、<mappers/>等属性
    	2、开发人员编写的XXXMapper.xml文件,比如<resultMap/>、sql标签
    提供了创建如下操作对象的方法:
    	1、Executor对象:MyBatis执行器,负责SQL语句的生成和查询缓存的维护
        2、StatementHandler对象:封装了JDBC Statement操作
        3、ParameterHandler对象:将用户传递的参数转换成JDBC Statement所需要的参数
        4、ResultSEtHandler对象:负责将JDBC返回的ResultSet结果集进行转换
    

进入到parser.parse()方法中:

public Configuration parse() {
  if (parsed) {
    throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  }
  parsed = true;
  /*
  	1. parser对象内部封装了XPath对象,
  	2. parser.evalNode("/configuration"))方法将mybatis-config.xml文件中的<configuration/>标签封装为		   XNode对象
  	3. parseConfiguration方法解析<configuration/>标签下面的子标签
  */
  parseConfiguration(parser.evalNode("/configuration"));
  return configuration;
}

进入到parseConfiguration方法中:

private void parseConfiguration(XNode root) {
  try {
    //issue #117 read properties first
    propertiesElement(root.evalNode("properties"));
    Properties settings = settingsAsProperties(root.evalNode("settings"));
    loadCustomVfs(settings);
    typeAliasesElement(root.evalNode("typeAliases"));
    pluginElement(root.evalNode("plugins"));
    objectFactoryElement(root.evalNode("objectFactory"));
    objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
    reflectorFactoryElement(root.evalNode("reflectorFactory"));
    settingsElement(settings);
    // read it after objectFactory and objectWrapperFactory issue #631
    environmentsElement(root.evalNode("environments"));
    databaseIdProviderElement(root.evalNode("databaseIdProvider"));
    typeHandlerElement(root.evalNode("typeHandlers"));
    //会进一步读取并且解析XXXMapper.xml文件
    mapperElement(root.evalNode("mappers"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MrVCI69f-1684509391270)(res/Mybatis源码分析/image-20230512171701204.png)]

该方法主要是解析<configuration/>标签中的子标签,这里需要重点看一下mapperElement(root.evalNode("mappers"))这行代码,开发人员并没有指定读取XXXMapper.xml文件,只是读取了mybatis-config.xml文件,而Mybatis在解析<myppers>标签时就会根据<mapper/>标签中的resource属性找到XXXMapper.xml,完成读取以及解析工作。

<!--注册mapper-->
<mappers>
    <package name=""/>
    <mapper resource="" class="" url=""/>
</mappers>

<!-- 例如 -->
<mappers>
    <mapper resource="UserDAOMapper.xml"/>
</mappers>

进入到mapperElement(root.evalNode("mappers"))方法中:

private void mapperElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        String mapperPackage = child.getStringAttribute("name");
        configuration.addMappers(mapperPackage);
      } else {
        String resource = child.getStringAttribute("resource");
        String url = child.getStringAttribute("url");
        String mapperClass = child.getStringAttribute("class");
        if (resource != null && url == null && mapperClass == null) {
          ErrorContext.instance().resource(resource);
          //读取xxxMapper.xml
          InputStream inputStream = Resources.getResourceAsStream(resource);
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
          //解析xxxMapper.xml文件
          mapperParser.parse();
        } else if (resource == null && url != null && mapperClass == null) {
          ErrorContext.instance().resource(url);
            //读取xxxMapper.xml
          InputStream inputStream = Resources.getUrlAsStream(url);
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            //解析xxxMapper.xml文件
          mapperParser.parse();
        } else if (resource == null && url == null && mapperClass != null) {
          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.");
        }
      }
    }
  }
}

进入到mapperParser.parse()方法中

public void parse() {
  if (!configuration.isResourceLoaded(resource)) {
    /*
    	与上面解析<configuration/>标签一样:
    	1. parser.evalNode("/mapper")方法将<mapper/>标签封装为XNode对象
    	2. configurationElement方法解析<mapper/>标签的子标签
    */
    configurationElement(parser.evalNode("/mapper"));
    configuration.addLoadedResource(resource);
    //设置命名空间
    bindMapperForNamespace();
  }

  parsePendingResultMaps();
  parsePendingCacheRefs();
  parsePendingStatements();
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M1oO82lm-1684509391271)(res/Mybatis源码分析/image-20230512172319592.png)]

进入到configurationElement(parser.evalNode("/mapper"))方法中:

private void configurationElement(XNode context) {
  try {
     //命名空间
    String namespace = context.getStringAttribute("namespace");
    if (namespace == null || namespace.equals("")) {
      throw new BuilderException("Mapper's namespace cannot be empty");
    }
    builderAssistant.setCurrentNamespace(namespace);
     //设置多个Mapper共用二级缓存
    cacheRefElement(context.evalNode("cache-ref"));
     //开启二级缓存
    cacheElement(context.evalNode("cache"));
     //解析parameterMap标签
    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
     //解析resultMap标签
    resultMapElements(context.evalNodes("/mapper/resultMap"));
     //解析sql标签
    sqlElement(context.evalNodes("/mapper/sql"));
     //解析增删改查sql语句,封装为MappedStatement标签
    buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
  }
}

进入到buildStatementFromContext(context.evalNodes("select|insert|update|delete"))方法中:

private void buildStatementFromContext(List<XNode> list) {
  if (configuration.getDatabaseId() != null) {
    buildStatementFromContext(list, configuration.getDatabaseId());
  }
  buildStatementFromContext(list, null);
}

private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
       //循环对每一个增删改查的sql标签进行解析
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
        //解析sql标签
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }

进入到statementParser.parseStatementNode()方法中:

public void parseStatementNode() {
   //sql的id值,对应Mapper接口方法名
  String id = context.getStringAttribute("id");
   //每一个sql语句都可以单独设置数据库环境
  String databaseId = context.getStringAttribute("databaseId");

  if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
    return;
  }

  Integer fetchSize = context.getIntAttribute("fetchSize");
   //超时
  Integer timeout = context.getIntAttribute("timeout");
   //参数Map
  String parameterMap = context.getStringAttribute("parameterMap");
   //参数类型
  String parameterType = context.getStringAttribute("parameterType");
  Class<?> parameterTypeClass = resolveClass(parameterType);
   //结果集映射Map
  String resultMap = context.getStringAttribute("resultMap");
   //结果集映射类型
  String resultType = context.getStringAttribute("resultType");
  String lang = context.getStringAttribute("lang");
  LanguageDriver langDriver = getLanguageDriver(lang);

  Class<?> resultTypeClass = resolveClass(resultType);
  String resultSetType = context.getStringAttribute("resultSetType");
  StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
  ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

  String nodeName = context.getNode().getNodeName();
  SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
  boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
   //刷新缓存
  boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
   //是否使用二级缓存
  boolean useCache = context.getBooleanAttribute("useCache", isSelect);
  boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

  // Include Fragments before parsing
  XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
  includeParser.applyIncludes(context.getNode());

  // Parse selectKey after includes and remove them.
  processSelectKeyNodes(id, parameterTypeClass, langDriver);
  
  // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
  SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
  String resultSets = context.getStringAttribute("resultSets");
  String keyProperty = context.getStringAttribute("keyProperty");
  String keyColumn = context.getStringAttribute("keyColumn");
  KeyGenerator keyGenerator;
  String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
  keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
  if (configuration.hasKeyGenerator(keyStatementId)) {
    keyGenerator = configuration.getKeyGenerator(keyStatementId);
  } else {
    keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
        configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
        ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
  }
 //将每一条sql相关的属性封装为一个MappedStatement
  builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
      fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
      resultSetTypeEnum, flushCache, useCache, resultOrdered, 
      keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}

执行完上述代码后就会将mybatis-config.xmlxxxMapper.xml文件全部解析完成,并且封装到Configuration对象中。接下来就可以根据Configuration对象SqlSessionFactory。

public SqlSessionFactory build(Configuration config) {
  return new DefaultSqlSessionFactory(config);
}

创建SqlSession

第二步代码:

//创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();

上面创建SqlSessionFactory使用的是子类DefaultSqlSessionFactory,进入到openSession()方法中:

public SqlSession openSession() {
  return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
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);
    //创建执行器Executor(由Configuration对象提供的创建的)
    final Executor executor = configuration.newExecutor(tx, execType);
    //创建数据库会话SQLSession
    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();
  }
}

执行Sql

第三步代码:

//执行SQL
List<User> users = sqlSession.selectList("edu.hzb.dao.UserDAO.selectList");

创建了SqlSession后,就可以进行执行增删改查操作了,以查询方法为例:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SOmautqD-1684509391272)(res/Mybatis源码分析/image-20230513184111974.png)]

进入到selectList()方法中,在第一步Mybatis初始化过程中就将xxxMapper.xml中的增删改查语句封装为MappedStatement对象并且存放在Configuration对象中。

public <E> List<E> selectList(String statement) {
  return this.selectList(statement, null);
}

@Override
public <E> List<E> selectList(String statement, Object parameter) {
  return this.selectList(statement, parameter, RowBounds.DEFAULT);
}

@Override
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
  try {
    //获取Sql语句对应的MappedStatement对象
    MappedStatement ms = configuration.getMappedStatement(statement);
    //执行查询方法,SqlSession只是门面,增删改查都会交给Executor执行
    return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
  } finally {
    ErrorContext.instance().reset();
  }
}

进入到executor.query方法中,

public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
   //sql语句
   BoundSql boundSql = ms.getBoundSql(parameter);
   //根据sql语句,参数等内容创建缓存的key
   CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
   //真正执行query方法
   return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}

继续进入到query方法中,这里首先会判断是否开启二级缓存,如果开启二级缓存

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) {
      //刷新二级缓存
      flushCacheIfRequired(ms);
       //使用二级缓存的条件之一就是<select/>标签中的useCache属性为true
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        @SuppressWarnings("unchecked")
        //查询二级缓存
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          //没有从二级缓存中获取到结果数据,继续执行SimpleExecutor的query方法
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //没有开启二级缓存,执行SimpleExecutor的query方法
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }

从上面这段代码就可以知道如下内容:

  1. Mybatis查询数据顺序:二级缓存 —> 一级缓存 —> 数据库

  2. 这里判断是否开启二级缓存,采用了装饰器设计模式,delegate对象默认是SimpleExecutor

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HpX1w0Ra-1684509391272)(res/Mybatis源码分析/image-20230513233835582.png)]

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aX2QF8ar-1684509391273)(res/Mybatis源码分析/image-20230513234041529.png)]

如果二级缓存没有命中或没有开启二级缓存,就会执行delegate.query方法,进入到delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql)这行代码中:

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());
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
   //清空一级缓存
  if (queryStack == 0 && ms.isFlushCacheRequired()) {
    clearLocalCache();
  }
  List<E> list;
  try {
    queryStack++;
     //从一级缓存中获取数据
    list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
    if (list != null) {
      //一级缓存命中了
      //这个方法主要针对的是CallableStatement,我们都是采用PreparedStatement,所以这行代码不会执行
      handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
    } else {
      //一级缓存没有命中,就会查询数据库(通过PreparedStatement.execute()方法执行Sql)
      list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    }
  } finally {
    queryStack--;
  }
  if (queryStack == 0) {
    for (DeferredLoad deferredLoad : deferredLoads) {
      deferredLoad.load();
    }
    deferredLoads.clear();
    if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
      clearLocalCache();
    }
  }
  return list;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值