引言
随着技术竞争日益激烈,针对常用ORM框架MyBatis,笔者计划推出系列文章。本系列涵盖SqlSessionFactory初始化原理、SqlSession执行流程、代理模式运行机制及总结,本文为第一篇,欢迎持续关注后续内容。
SqlSessionFactory
基于MyBatis的应用程序核心在于SqlSessionFactory实例。该实例可通过SqlSessionFactoryBuilder获取,而构建器则能依据XML配置文件或预先配置的Configuration实例来生成SqlSessionFactory。
从XML文件构建SqlSessionFactory十分简便,推荐在类路径下使用资源文件进行配置。当然,也可使用任意InputStream实例,如基于文件路径字符串或file:// URL构造的流。MyBatis提供的Resources工具类简化了从类路径或其他位置加载资源的操作。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
XML配置文件包含MyBatis系统的核心设置,如获取数据库连接的数据源(DataSource)以及控制事务作用域的事务管理器(TransactionManager)。下文将探讨XML配置细节,此处先给出简单示例。
<?xml version="1.0" encoding="UTF-8" ?>
XML文件中可配置众多选项,上述示例仅列出关键部分。注意XML头部声明用于验证文档正确性。environment元素包含事务管理和连接池配置,mappers元素则定义了一组映射器,其对应的XML映射文件包含SQL代码和映射定义信息。
不使用 XML 构建 SqlSessionFactory
若倾向于直接从Java代码而非XML文件创建配置,或希望自定义配置建造器,MyBatis提供了完整的配置类,涵盖所有与XML等价的配置项。
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
需注意,示例中configuration添加了一个映射器类(mapper class)。映射器类是包含SQL映射注解的Java类,旨在避免依赖XML文件。然而,受限于Java注解及某些MyBatis映射的复杂性,多数高级映射(如嵌套联合映射)仍需XML配置。若存在同名XML配置文件,MyBatis会自动查找并加载它(例如基于类路径和BlogMapper.class加载BlogMapper.xml),具体细节后续讨论。
SqlSessionFactoryBuilder
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
build方法:
// 1.我们最初调用的build
public SqlSessionFactory build(InputStream inputStream) {
//调用了重载方法
return build(inputStream, null, null);
}
// 2.调用的重载方法
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
// 创建 XMLConfigBuilder, XMLConfigBuilder是专门解析mybatis的配置文件的类
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
// 执行 XML 解析
// 创建 DefaultSqlSessionFactory 对象
return build(parser.parse());
} catch (Exception e) {
//···
}
}
parser.parse()
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
// 标记已解析
parsed = true;
// parser.evalNode("/configuration"),
// 通过xpath 读取配置文件的节点,将读取出配置文件的所以节点
//
//
//
//
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
parseConfiguration(XNode root)
// 解析每个节点 这里每个方法进去都会有很多配置,这里就不一一解析,大家感兴趣可以看看,
// settingsElement(settings);mapperElement(root.evalNode("mappers"));
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
// 解析 标签
propertiesElement(root.evalNode("properties"));
// 解析 标签
Properties settings = settingsAsProperties(root.evalNode("settings"));
// 加载自定义的 VFS 实现类
loadCustomVfs(settings);
// 解析 标签
typeAliasesElement(root.evalNode("typeAliases"));
// 解析 标签
pluginElement(root.evalNode("plugins"));
// 解析 标签
objectFactoryElement(root.evalNode("objectFactory"));
// 解析 标签
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
// 解析 标签
reflectorFactoryElement(root.evalNode("reflectorFactory"));
// 赋值 到 Configuration 属性
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);
}
}
// 获取mapper
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 {
// 读取resource 标签
String resource = child.getStringAttribute("resource");
// 读取url 标签
String url = child.getStringAttribute("url");
// 读取注解
String mapperClass = child.getStringAttribute("class");
// 根据不同的方式完成
if (resource != null && url == null && mapperClass == null) {
ErrorContext.instance().resource(resource);
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
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.");
}
}
}
}
}
private void settingsElement(Properties props) {
configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
.....
configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
}
mapperParser.parse();
// 这里我们先看一下 mapperParser.parse();方法 懂得原理,都是类似的
public void parse() {
if (!configuration.isResourceLoaded(resource)) {
// 加载 mapper所有子节点
configurationElement(parser.evalNode("/mapper"));
configuration.addLoadedResource(resource);
// 绑定 Namespace
bindMapperForNamespace();
}
// 构建ResultMap
parsePendingResultMaps();
parsePendingCacheRefs();
parsePendingStatements();
}
// 这里将解析整个 xml文件
private void configurationElement(XNode context) {
try {
String namespace = context.getStringAttribute("namespace");
if (namespace == null || namespace.isEmpty()) {
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"));
sqlElement(context.evalNodes("/mapper/sql"));
// 解析标签,
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);
}
}
// 关于注解的方式的parse
public void parse() {
String resource = type.toString();
if (!configuration.isResourceLoaded(resource)) {
loadXmlResource();
configuration.addLoadedResource(resource);
assistant.setCurrentNamespace(type.getName());
parseCache();
parseCacheRef();
for (Method method : type.getMethods()) {
if (!canHaveStatement(method)) {
continue;
}
if (getAnnotationWrapper(method, false, Select.class, SelectProvider.class).isPresent()
&& method.getAnnotation(ResultMap.class) == null) {
parseResultMap(method);
}
try {
parseStatement(method);
} catch (IncompleteElementException e) {
configuration.addIncompleteMethod(new MethodResolver(this, method));
}
}
}
parsePendingMethods();
}
至此,MyBatis的初始化工作完成,主要涉及两项核心任务:
- 解析核心配置文件至Configuration对象,解析映射配置文件至MappedStatement对象,并将其保存在Configuration的对应Map中。
- 创建DefaultSqlSessionFactory并返回。
通过上述代码分析,总结了使用的重要类。经过图中的装配流程,最终返回SqlSessionFactory,其最终实现为DefaultSqlSessionFactory。关于DefaultSqlSessionFactory的详细介绍将在下篇文章讲解,感兴趣的朋友请持续关注!

拓展
读者可能会疑惑,上述配置基于文件方式,但Spring Boot并无此类配置文件,如何实现?实际上,Spring Boot是通过自定义配置完成的。
@Configuration
// 实例化 SqlSessionFactory
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
// MybatisProperties 我们常用的配置
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class})
public class MybatisAutoConfiguration implements InitializingBean {}
至此,关于解析MyBatis SqlSessionFactory初始化原理的文章介绍完毕。更多相关内容请搜索本站历史文章或继续阅读后续文章,感谢大家的支持!