【深入理解MyBatis】- 09Mybatis 从数据库中读取数据源码分析

前景回顾

01从数据库中读取数据过程章节我们从整体明白了使用Mybatis访问数据库的过程,现在从代码实现的角度来看Mybatis是如何实现的

Mybatis叙述简述

  • 构造由XML配置的对象Configuration,下面说明一个最简单的系统XML配置,Configuration包含数据库连接管理等信息
<?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>
  • 对象Configuration还包含了映射器配置信息,这部分信息也是Mybatis最重要的部分,需要使用者来书写的部分,如上述的BlogMapper.xml,也就是说Configuration包含了原始的映射器XML配置信息
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="priv.mybatis.example01.dao.RoleMapper">
  <select id="selectRole" resultType="priv.mybatis.example01.domain.Role" >
    select * from Role where id = #{hhh}
  </select>
    <select id="selectRole2" resultType="priv.mybatis.example01.domain.Role" >
    select * from Role where id = #{id}
  </select>
</mapper>

  • 绑定映射器XML中的SQL语句和配置信息封装成对象MappedStatement,MappedStatement含有某一个SQL结点的所有信息,如下,MappedStatement对象也由对象Configuration统一储存
  <select id="selectRole2" resultType="priv.mybatis.example01.domain.Role" >
    select * from Role where id = #{id}
  </select>
  • SQL语句的获取,如openSession.selectOne("priv.mybatis.example01.dao.RoleMapper.selectRole", 1);,通过关键字priv.mybatis.example01.dao.RoleMapper.selectRole
    对象Configuration中获取SQL封装对象MappedStatement,

  • SQL语句的执行,Mybatis执行sql语句是通过执行器Executor,负责管理整个SQL的执行过程。负责执行SQL语句相关是StatementHandler对象,负责整个SQL语句的预处理,以及请求SQL以后,对返回数据的映射,其中需要执行这些过程,需要两个其他对象的辅助

    1. ParameterHandler 帮助StatementHandler封装SQL,主要负责对用户传递的参数转换成SQL所需要的参数
    2. ResultSetHandler 帮助StatementHandler返回执行SQL后的结果,主要是对JDBC ResultSet结果集转换

Mybatis源码跟踪

注意:这里不建议没有阅读过源码的人了解,因为这不是逐行逐行的阅读,只是讲解关键步骤

  • 全局配置XML解析,XMLConfigBuilder

方法parseConfiguration为全局XML配置的解析

	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"));
			// 映射器
			mapperElement(root.evalNode("mappers"));
		} catch (Exception e) {
			throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
		}
	}

对应着Mybatis支持的配置属性,这里也就是为什么MyBatis的节点顺序错乱了为什么会报错的原因,因为源码就是按照默认顺序解析的,对应着下图
在这里插入图片描述

我们上述的例子配置数据库连接信息,那就看看environmentsElement属性的解析吧

	private void environmentsElement(XNode context) throws Exception {
		if (context != null) {
			if (environment == null) {
				// 默认使用标识为default配置结点
				environment = context.getStringAttribute("default");
			}
			// 这里是个循环,也就是支持多个配置信息,通过id来标识
			for (XNode child : context.getChildren()) {
				String id = child.getStringAttribute("id");
				if (isSpecifiedEnvironment(id)) {
					// 事务管理器
					TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
					// 数据源
					DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
					DataSource dataSource = dsFactory.getDataSource();
					Environment.Builder environmentBuilder = new Environment.Builder(id).transactionFactory(txFactory)
							.dataSource(dataSource);
					configuration.setEnvironment(environmentBuilder.build());
				}
			}
		}
	}
  <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>

可以看出,通过配置信息,是想构造事务管理器和数据源对象,同时我们也可以看出Mybatis是支持多数据源的,构造好以后,都赋值给configuration对象管理,虽然有多个数据源,但是同一个SqlSessionFactoryBuilder对象只能使用一个数据源,因为有方法sSpecifiedEnvironment(id)匹配,这里不再复述,感兴趣可以阅读一下这段源码,难度等级较低

  • 业务*Mapper.xml配置解析, XMLMapperBuilder

可以看出,Mapper配置元素十分丰富,这也是Mybatis支持最强大的地方,但是由于我们的例子,只使用到了简单的配置信息,那我们可以跳过很多功能不用看,直接查看方法buildStatementFromContext

	private void configurationElement(XNode context) {
		try {
			// namespace对应接口,例:priv.mybatis.example01.dao.RoleMapper
			String namespace = context.getStringAttribute("namespace");
			if (namespace == null || namespace.equals("")) {
				throw new BuilderException("Mapper's namespace cannot be empty");
			}
			builderAssistant.setCurrentNamespace(namespace);
			/**
			 * SQL 映射文件只有很少的几个顶级元素
			 * cache – 该命名空间的缓存配置。
			 * cache-ref – 引用其它命名空间的缓存配置。
			 * resultMap – 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素。
			 * parameterMap – 老式风格的参数映射。此元素已被废弃,并可能在将来被移除!请使用行内参数映射。文档中不会介绍此元素。
			 * sql – 可被其它语句引用的可重用语句块。
			 * insert – 映射插入语句。
			 * update – 映射更新语句。
			 * delete – 映射删除语句。
			 * select – 映射查询语句
			 */
			cacheRefElement(context.evalNode("cache-ref"));
			cacheElement(context.evalNode("cache"));
			parameterMapElement(context.evalNodes("/mapper/parameterMap"));
			resultMapElements(context.evalNodes("/mapper/resultMap"));
			sqlElement(context.evalNodes("/mapper/sql"));
			
			// 这里只有select方法,方法入口
			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);
		}
	}

查看方法statementParser.parseStatementNode()
在这里插入图片描述
方法parseStatementNode(),也就是对应XML 映射器语句解析,包括
insert – 映射插入语句。
update – 映射更新语句。
delete – 映射删除语句。
select – 映射查询语句。

	public void parseStatementNode() {
		// 方法名称
		String id = context.getStringAttribute("id");
		String databaseId = context.getStringAttribute("databaseId");

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

		Integer fetchSize = context.getIntAttribute("fetchSize");
		Integer timeout = context.getIntAttribute("timeout");
		String parameterMap = context.getStringAttribute("parameterMap");
		String parameterType = context.getStringAttribute("parameterType");
		Class<?> parameterTypeClass = resolveClass(parameterType);
		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
		// 可重用的 SQL 代码片段, <include>
		XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
		includeParser.applyIncludes(context.getNode());

		// Parse selectKey after includes and remove them.
		// 主键生成器<selectKey>
		processSelectKeyNodes(id, parameterTypeClass, langDriver);

		// Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
		// SQL 对象封装
		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;
		}

		builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout,
				parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache,
				resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
	}

我们的例子使用select,select 元素允许你配置很多属性来配置每条语句的行为细节。

<select
  id="selectPerson"
  parameterType="int"
  parameterMap="deprecated"
  resultType="hashmap"
  resultMap="personResultMap"
  flushCache="false"
  useCache="true"
  timeout="10"
  fetchSize="256"
  statementType="PREPARED"
  resultSetType="FORWARD_ONLY">

我们可以看出,将上述元素解析以后,执行方法builderAssistant.addMappedStatement,将保存成MappedStatement对象,最终也是保存到configuration对象下

	...省略多处代码
    // XML结点最终映射为MappedStatement对象
    MappedStatement statement = statementBuilder.build();
    configuration.addMappedStatement(statement);

  • SQL语句的执行
    在这里插入图片描述
    图左面为SQL执行器,对应的Mybatis配置
    defaultExecutorType 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 SIMPLE REUSE BATCH

CachingExecutor是一个变体代理类,负责转发到具体的执行器,默认是PreparedStatement执行器,上述Mapper解析中含有代码StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));,也就是说,这个是SQL语句级别的,不同的SQL语句可以分开设置

默认为SIMPLE 就是普通的执行器:SimpleExecutor,对应的我们的查询,找到方法doQuery

	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();
			// SQL全局操作对象
			StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds,
					resultHandler, boundSql);
			// 设置Statement对象,SQL查询前
			stmt = prepareStatement(handler, ms.getStatementLog());
			// SQL查询,并解析数据库返回数据
			return handler.<E>query(stmt, resultHandler);
		} finally {
			closeStatement(stmt);
		}
	}

其中到这里基本上明白了Mybatis主要思想,要阅读源码最主要还是自己看很多遍,看博客影响不深刻,很多细节也体现不了,而且特定问题要特定分析,这里抛砖引玉一下StatementHandler 对象,也就是上述图右的对象StatementHandler ,为什么会有四个实现类,分别代表什么含义

通过变体的代理类RoutingStatementHandler(这个是一个特殊的委托设计模式,Mybatis很多地方有使用,如Cache,Executor等),我们查看其中的实现可以发现,其他的三个类,分别代表了数据库SQL的三种处理方式STATEMENT、PREPARED、CALLABLE

public class RoutingStatementHandler implements StatementHandler {

  private final StatementHandler delegate;

  public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }
  }
  ....忽略很多代码
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值