一、先看SqlSessionFactory创建过程流程图(配置文件都要解析封装到Configuration对象中)
二、基于源码解读SqlSessionFactory创建过程
(1)、首先把mybatis配置文件读取到流中,传给SqlSessionFactoryBuilder().build()
InputStream is = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlsessionFactory=new SqlSessionFactoryBuilder().build(is);
(2)首先看build中XMLConfigBuilder(继续建造者模式)解析这个配置文件
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
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.
}
}
}
(3)parser.parse()去解析配置文件中的configuration对应信息,然后返回configuration
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
(4)我们再看parseConfiguration中解析了配置文件中那些信息,可以看到配置文件中的settings、plugins插件、enviroments、mappers、以及typehandlers类型转换器等,详解可以进去到方法中自己看
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(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);
}
}
(5)生成configuration之后返回到(2)步中的build(configuration),创建了对应的DefaultSqlSessionFactory,
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
mybatis源码api_sqlSessionFactory创建过程
原文:https://www.cnblogs.com/kjcc/p/13073074.html