mybatis源码分析(sqlSessionFactory生成过程)

  1. mybatis框架在现在各个IT公司的使用不用多说,这几天看了mybatis的一些源码,赶紧做个笔记.

  2. 看源码从一个demo引入如下:

public class TestApp {
private static SqlSessionFactory sqlSessionFactory;
static {
InputStream inputStream;
String resource = "mybatis-config.xml";
try {
       //获取全局配置文件的数据流
inputStream = Resources.getResourceAsStream(resource);
//获取sqlSessionFactory
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}

如上代码获取SQLSessionFactory实例对象,下来进入SqlSessionFactoryBuilder类中看其如何通过build方法创建SQLsessionFactory对象的:

//外部调用的SQLSessionFactoryBuilder的build方法: 
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}

上面的方法调用下面的三个参数的build方法

  public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
    //这里创建的是mybatis全局配置文件的解析器
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
//解析器parser调用parse()方法对全局配置文件进行解析,返回一个Configuration对象,这个对象包含了mybatis全局配置文件中以及mapper文件中的所有配置信息
    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.
}
}
}

接着调用SqlSessionFactoryBuilder中的build(x)方法,创建一个defaultSQLSessionFactory对象返回给用户

// 入参是XMLConfigBuilder解析器解析后返回的Configuration对象,这个方法中创建一个defaultSqlSessonFactory对象给用户,其中包含一个Configuration对象属性
// 所以我们获取的SQLSessionFactory对象中就包含了项目中mybatis配置的所有信息

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

上面的几个步骤中创建了sqlSessionFactory对象,下来我们看mybatis如何解析配置文件以及获取Configuration对象:

  3. mybaties解析配置文件

进入上面提到的XMLConfigBuilder parser.parse()方法中.

//类XMLConfigBuilder
//parsed第一次解析配置文件时默认为FALSE,下面设置为true,也就是配置文件只解析一次

public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
//这里解析开始解析配置文件,这里的parser.evelNode("/configuration")是获取元素"configuration"下面的所有信息,也就是主配置文件的根节点下的所有配置
parseConfiguration(parser.evalNode("/configuration"));
//将配置文件解析完后,也就是对configuration对象组装完成后,返回组装(设值)后的configuration实例对象
   return configuration;
}
进入parseConfiguration()方法中,传入的是配置文件的主要信息
private void parseConfiguration(XNode root) {
try {
//这里解析配置文件中配置的properties元素,其作用是如果存在properties元素的配置,则解析配置的property属性,存放到configuration.setVariables(defaults)中去,具体看源码这里不详述;
propertiesElement(root.evalNode("properties")); //issue #117 read properties first
//解析别名
    typeAliasesElement(root.evalNode("typeAliases"));
//解析插件
pluginElement(root.evalNode("plugins"));
//这两个暂时不懂
    objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
//解析全局配置属性settings
settingsElement(root.evalNode("settings"));
environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
//解析类型转换器
typeHandlerElement(root.evalNode("typeHandlers"));
    //以上的解析结果都存放到了configuration的相关属性中,下来这个解析配置的mappers节点以及其对应的mapper文件,我们主要看下这个.
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}

接入方法 mapperElement(xxxx)进行mapper文件的解析,其参数是通过root.evalNode("mappers");解析之后的<mappers>xxxxx</mappers>节点

private void mapperElement(XNode parent) throws Exception {
//判断是否配置了mapper文件,如果没有就直接退出
  if (parent != null) {
    //这里获取所有的mappers的子元素,然后遍历挨个解析
for (XNode child : parent.getChildren()) {
//解析以包方式进行的配置
    if ("package".equals(child.getName())) {
String mapperPackage = child.getStringAttribute("name");
configuration.addMappers(mapperPackage);
} else {
//这里是解析以文件方式配置的mapper,文件配置方式包括三种:resource,url,mapperClass;今天我们主要看以resource方式配置的解析
      //获取文件配置路径
String resource = child.getStringAttribute("resource");
String url = child.getStringAttribute("url");
String mapperClass = child.getStringAttribute("class");
       //此种方式配置: <mapper resource="com/wfl/aries/mapper/UserMapper.xml"/>
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
       //获取mapper配置文件的流
InputStream inputStream = Resources.getResourceAsStream(resource);
       //创建mapper解析器
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
//解析mapper文件开始
       mapperParser.parse();
} else if (resource == null && url != null && mapperClass == null) {
ErrorContext.instance().resource(url);
InputStream inputStream = Resources.getUrlAsStream(url);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
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.");
}
}
}
}
}

进入mapper解析器

//类XMLMapperBuilder中
//解析mapper的方法
public void parse() {
//判断是否已经解析和加载过了,如果没有则进行解析
  if (!configuration.isResourceLoaded(resource)) {
    //解析mapper传入的参数是mapper文件的根节点
configurationElement(parser.evalNode("/mapper"));
    //将该mapper的namespace添加到configuration的对象的一个set集合中去
configuration.addLoadedResource(resource);
    //后续的mapper文件配置属性和configuration对象关联
bindMapperForNamespace();
} parsePendingResultMaps();
parsePendingChacheRefs();
parsePendingStatements();
}

具体的解析mapper文件的方法

 private void configurationElement(XNode context) {
try {
    //获取命名空间
String namespace = context.getStringAttribute("namespace");
//如果命名空间为空则抛出异常
    if (namespace.equals("")) {
throw new BuilderException("Mapper's namespace cannot be empty");
}
builderAssistant.setCurrentNamespace(namespace);
cacheRefElement(context.evalNode("cache-ref"));
cacheElement(context.evalNode("cache"));
//处理参数映射配置
parameterMapElement(context.evalNodes("/mapper/parameterMap"));
//处理结果映射配置
resultMapElements(context.evalNodes("/mapper/resultMap"));
//处理sql片段
    sqlElement(context.evalNodes("/mapper/sql"));
    //解析statment
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
} catch (Exception e) {
throw new BuilderException("Error parsing Mapper XML. Cause: " + e, e);
}
}

解析statement的方法

//入参是一个statement的列表,也就是mapper中配置的所有的startement文件
private void buildStatementFromContext(List<XNode> list) {
if (configuration.getDatabaseId() != null) {
buildStatementFromContext(list, configuration.getDatabaseId());
}
buildStatementFromContext(list, null);
} //被上面的方法调用解析statement
private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
//循环变量解析每一个statement
  for (XNode context : list) {
    //创建一个statement解析器
final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
try {
     //解析单个statement
statementParser.parseStatementNode();
} catch (IncompleteElementException e) {
configuration.addIncompleteStatement(statementParser);
}
}
}

//解析statement读取配置文件中配置的statement的相关属性,并取值之后创建一个mapperdStatement
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
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))
? new Jdbc3KeyGenerator() : new NoKeyGenerator();
} builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}

创建一个mapperdStatement并添加到configuration的mappedStatements的map集合中.

public MappedStatement addMappedStatement(
String id,
SqlSource sqlSource,
StatementType statementType,
SqlCommandType sqlCommandType,
Integer fetchSize,
Integer timeout,
String parameterMap,
Class<?> parameterType,
String resultMap,
Class<?> resultType,
ResultSetType resultSetType,
boolean flushCache,
boolean useCache,
boolean resultOrdered,
KeyGenerator keyGenerator,
String keyProperty,
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) { if (unresolvedCacheRef) throw new IncompleteElementException("Cache-ref not yet resolved"); id = applyCurrentNamespace(id, false);
boolean isSelect = sqlCommandType == SqlCommandType.SELECT; MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType);
statementBuilder.resource(resource);
statementBuilder.fetchSize(fetchSize);
statementBuilder.statementType(statementType);
statementBuilder.keyGenerator(keyGenerator);
statementBuilder.keyProperty(keyProperty);
statementBuilder.keyColumn(keyColumn);
statementBuilder.databaseId(databaseId);
statementBuilder.lang(lang);
statementBuilder.resultOrdered(resultOrdered);
statementBuilder.resulSets(resultSets);
setStatementTimeout(timeout, statementBuilder); setStatementParameterMap(parameterMap, parameterType, statementBuilder);
setStatementResultMap(resultMap, resultType, resultSetType, statementBuilder);
setStatementCache(isSelect, flushCache, useCache, currentCache, statementBuilder); MappedStatement statement = statementBuilder.build();
configuration.addMappedStatement(statement);
return statement;
}

解析完所有的mapper以及其中的statement之后,所有的解析就到此结束,返回configuration对象给SqlSessionFactoryBuilder对象,创建DefaultSqlSessionFactory.

注:  其中SqlSessionFactory是接口,DefaultSqlSessionFactory实现了其SQLSessionFactory所以最后创建的是DefaultSqlSessionFactory

由此获取到了sessionFactory;

mybatis源码分析(一)的更多相关文章

  1. MyBatis源码分析-MyBatis初始化流程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  2. MyBatis源码分析-SQL语句执行的完整流程

    MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以对配置和原生Map使用简 ...

  3. MyBatis源码分析(5)——内置DataSource实现

    @(MyBatis)[DataSource] MyBatis源码分析(5)--内置DataSource实现 MyBatis内置了两个DataSource的实现:UnpooledDataSource,该 ...

  4. MyBatis源码分析(4)—— Cache构建以及应用

    @(MyBatis)[Cache] MyBatis源码分析--Cache构建以及应用 SqlSession使用缓存流程 如果开启了二级缓存,而Executor会使用CachingExecutor来装饰 ...

  5. MyBatis源码分析(3)—— Cache接口以及实现

    @(MyBatis)[Cache] MyBatis源码分析--Cache接口以及实现 Cache接口 MyBatis中的Cache以SPI实现,给需要集成其它Cache或者自定义Cache提供了接口. ...

  6. MyBatis源码分析(2)—— Plugin原理

    @(MyBatis)[Plugin] MyBatis源码分析--Plugin原理 Plugin原理 Plugin的实现采用了Java的动态代理,应用了责任链设计模式 InterceptorChain ...

  7. 【MyBatis源码分析】select源码分析及小结

    示例代码 之前的文章说过,对于MyBatis来说insert.update.delete是一组的,因为对于MyBatis来说它们都是update:select是一组的,因为对于MyBatis来说它就是 ...

  8. MyBatis源码分析之环境准备篇

    前言 之前一段时间写了[Spring源码分析]系列的文章,感觉对Spring的原理及使用各方面都掌握了不少,趁热打铁,开始下一个系列的文章[MyBatis源码分析],在[MyBatis源码分析]文章的 ...

  9. Mybatis源码分析-BaseExecutor

    根据前文Mybatis源码分析-SqlSessionTemplate的简单分析,对于SqlSession的CURD操作都需要经过Executor接口的update/query方法,本文将分析下Base ...

  10. Mybatis源码分析-StatementHandler

    承接前文Mybatis源码分析-BaseExecutor,本文则对通过StatementHandler接口完成数据库的CRUD操作作简单的分析 StatementHandler#接口列表 //获取St ...

随机推荐

  1. 【Mysql知识补充】

    一.子查询 1.定义 子查询是将一个查询语句嵌套在另一个查询语句中.内层查询语句的查询结果,可以为外层查询语句提供查询条件.子查询中可以包含:IN.NOT IN.ANY.ALL.EXISTS 和 NO ...

  2. CATransition

    CATransition *transition = [CATransition animation];    transition.duration = 1.0f;         /* 间隔时间* ...

  3. TCP/IP协议栈 -----链路层

    这节说一下链路层和ARP RARP协议 链路层: 在协议栈中链路层的目的有三个:1. 为IP模块发送或接受数据包 2.为ARP模块发送或接受ARP请求 3. 为RARP模块发送或接受RARP请求. 让 ...

  4. Mac关机时处于黑屏状态

    PS:不知道大家有没有遇到过mac电脑关机就黑屏,只有一个箭头,还可以滑动箭头,但就是黑屏状态,等个好长时间还是关不了机,因此我查了好多资料,原因是在关机时,mac要先关掉其他软件或者保存进程以备下次 ...

  5. mysql 存储过程 小实例

    咱们先建个表吧 [SQL] 纯文本查看 复制代码 ? 1 2 3 4 5 6     CREATE TABLE `test1` (   `id` int(10) unsigned NOT NULL A ...

  6. yii2.0中数据缓存之增删改查

    public function actionSss(){ /* * 获取到缓存 * 这里是获取的是根目录下 的common/main.php中的缓存类组件 * */ $cache=\Yii::$app ...

  7. Retrofit网络请求库应用02——json解析

    PS:上一篇写了Retrofit网络请求库的简单使用,仅仅是获取百度的源码,来证明连接成功,这篇讲解如何解析JSON数据,该框架不再是我们之前自己写的那样用JsonArray等来解析,这些东西,我们都 ...

  8. 站在 Android 开发的角度,聊聊 Airbnb 的 Lottie!!!

    一.前言 你有没有遇上一些设计师,对一些酷炫的动画着迷,喜欢根据场景设计出可爱而流畅的动画.但是在实际工作中,哪怕开发人员也觉得这些动画非常的棒,可我们知道,越是定制化的动画,实现起来将会越麻烦和耗时 ...

  9. PHP递归解决兔子问题,面试必备

    接到面试通知辗转反侧,一直在默念明天改如何介绍自己的项目经验等.早早的起床,洗漱,把自己的总结的问题自问自答了一些.匆匆吃了早饭,挤进让人面目狰狞的地铁,此时什么都不顾,只盼着赶紧下地铁.终于提前半小 ...

  10. js图片懒加载(滚动加载)是否生效

    一.什么是懒加载? 对未出现在视野范围内的图片先不进行加载,等到出现在视野范围才去加载. 二.为什么使用懒加载? 懒加载的主要目的是作为服务器前端的优化,减少请求数或延迟请求数. 理论性知识大家都有自 ...