mybatis从配置读取到打开连接的源码分析
1) 读取Mybaits的主配置配置文件
Reader reader = Resources.getResourceAsReader(resource);
2) 返回该文件的输入流
/*
* Returns a resource on the classpath as a Reader object
*
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
3) 读取配置文件流并将这些配置信息存放到Configuration类中。
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
PS: XMLConfigBuilder是创建一个配置文件流的解析对象XMLConfigBuilder,其实这里是将环境和配置文件流赋予解析类
parser.parse()是解析配置文件流,将配置信息放到Configuration,返回一个Configuration对象
4) XMLConfigBuilder初始化
private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
super(new Configuration());
ErrorContext.instance().resource("SQL Mapper Configuration");
this.configuration.setVariables(props);
this.parsed = false;
this.environment = environment;
this.parser = parser;
}
5) XMLConfigBuilder的parse方法
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each MapperConfigParser can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
PS:解析的内容主要是在parseConfiguration方法中,它主要完成的工作是读取配置文件的各个节点,然后将这些数据映射到内存配置对象Configuration中。
6) parseConfiguration方法
private void parseConfiguration(XNode root) {
try {
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"));
settingsElement(root.evalNode("settings"));
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);
}
}
7) 最后的build方法其实是传入配置对象进去,创建DefaultSqlSessionFactory实例出来.
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
PS: DefaultSqlSessionFactory是SqlSessionFactory的默认实现.
8) 获得SqlSessionFactory后,可以通过openSession()方法获得SqlSession对象
SqlSession sqlSession = factory.openSession();
PS: 通过调用DefaultSqlSessionFactory的openSession方法返回一个SqlSession实例。
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
9) openSession方法调用openSessionFromDataSource方法
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
//获取配置信息里面的环境信息,这些环境信息都是包括使用哪种数据库,连接数据库的信息,事务
final Environment environment = configuration.getEnvironment();
//根据环境信息关于事务的配置获取事务工厂
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
//从事务工厂获取一个事务实例
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//从配置信息中获取一个执行器实例
final Executor executor = configuration.newExecutor(tx, execType, autoCommit);
//返回SqlSession的一个默认实例
return new DefaultSqlSession(configuration, executor);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
传入参数说明:
(1)ExecutorType:执行类型,ExecutorType主要有三种类型:SIMPLE, REUSE, BATCH,默认是SIMPLE,都在枚举类ExecutorType里面。
(2)TransactionIsolationLevel:事务隔离级别,都在枚举类TransactionIsolationLevel中定义。
(3)autoCommit:是否自动提交,主要是事务提交的设置。
DefaultSqlSession是SqlSession的实现类,该类主要提供操作数据库的方法给开发人员使用。
小结:
1) 读取Mybatis的主配置文件,并将文件读成文件流形式(InputStream)。
2) 先从主配置文件流中读取文件的各个节点信息并存放到Configuration对象中。
3) 再读取mappers节点的引用文件,并将这些文件的各个节点信息存放到Configuration对象。
4) 根据Configuration对象的信息获取数据库连接,并设置连接的事务隔离级别等信息,将经过包装数据库连接对象SqlSession接口返回,DefaultSqlSession是SqlSession的实现类,所以这里返回的是DefaultSqlSession,SqlSession接口里面就是对外提供的各种数据库操作。

浙公网安备 33010602011771号