SqlSessionFactory的创建过程原理

上一篇 << 下一篇 >>>SqlSession的创建过程


1.初始化XMLConfigBuilder类,并装载XPathParser解析器

XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);

2.配置文件解析parser.parse()

configuration
|--- properties
|--- settings
|--- typeAliases
|--- typeHandlers
|--- objectFactory
|--- plugins
|--- environments
|--- |--- environment
|--- |--- |--- transactionManager
|--- |--- |__ dataSource
|__ mappers

XMLConfigBuilder.parsed = true; --设置全局变量,只允许装载一次
return XMLConfigBuilder.configuration;--结果返回

核心代码:

//XMLConfigBuilder解析从配置文件根目录(/configuration)开始
this.parseConfiguration(this.parser.evalNode("/configuration"));

//设置configuration的环境,包含有id、事务及数据源信息
this.environmentsElement(root.evalNode("environments"));
this.configuration.setEnvironment(environmentBuilder.build());
class Environment {
String id;
TransactionFactory transactionFactory;
DataSource dataSource;
}

//支持resource、package等多种方式
this.mapperElement(root.evalNode("mappers"));
resource:mappers/UserMapper.xml inputStream为具体的流内容
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, this.configuration, resource, this.configuration.getSqlFragments());
mapperParser.parse();

解析mapper文件组装sql语句并加入到configuration中
this.configurationElement(this.parser.evalNode("/mapper"));
                    --this.buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
                                XMLStatementBuilder statementParser = new XMLStatementBuilder(this.configuration, this.builderAssistant, context, requiredDatabaseId);
                                statementParser.parseStatementNode();--组装sql语句
                                this.configuration.addMappedStatement(statement);--加入到configuration中

//设置资源文件已解析
this.configuration.loadedResources.add("mappers/UserMapper.xml");

//设置mapperRegistry
this.bindMapperForNamespace();
 this.configuration.mapperRegistry.hasMapper(接口类:com.jgspx.mapper.UserMapper);
                this.configuration.loadedResources.add("namespace:" + namespace);

1.BaseBuilder:所有解析器的父类,包含配置文件实例,为解析文件提供的一些通用的方法;
2.XMLConfigBuilder: 主要负责解析 mybatis-config.xml;
3.XMLMapperBuilder: 主要负责解析映射配置 Mapper.xml 文件;
4.XMLStatementBuilder: 主要负责解析映射配置文件中的 SQL 节点;

3.初始化并返回默认的sessionfactory

return new DefaultSqlSessionFactory(config);

推荐阅读:
<< << << << << << << << << <<

你可能感兴趣的:(SqlSessionFactory的创建过程原理)