mybatis运行开始时,使用Resources类将磁盘上面的核心配置文件加载到内存中,得到一个输入流。
InputStream is = Resources.getResourceAsStream("mybatis.xml");
然后,通过输入流作为参数传递给XMLConfigBuilder,创建一个XMLConfigBuilder对象。XMLConfigBuilder对象调用parse方法,得到Configuration对象。它保存了磁盘中核心配置文件的信息。然后Configuration对象作为参数传递给DefaultSqlSessionFactory,得到DefaultSqlSessionFactory对象。DefaultSqlSessionFactory对象就是下面的factory。
// 自己写的
factory = new SqlSessionFactoryBuilder().build(is);
// mybatis内部执行的
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
SqlSessionFactory localSqlSessionFactory = build(parser.parse());
return localSqlSessionFactory;
} catch (Exception e) {
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
}
}
}
public Configuration parse() {
if (this.parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
this.parsed = true;
parseConfiguration(this.parser.evalNode("/configuration"));
return this.configuration;
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
然后,执行factory
.openSession().调用DefaultSqlSessionFactory对象的openSessionFromDataSource方法,创建Environment ,TransactionFactory ,Executor对象,保存Configuration对象中的数据。 获得一个DefaultSqlSession对象,就是session。
//自己写的
SqlSession session = factory.openSession(/*事务自动提交参数true*/);
//mybatis内部执行的方法
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
boolean autoCommit) {
Exception exception;
Transaction tx = null;
DefaultSqlSession defaultsqlsession;
try {
Environment environment = configuration.getEnvironment();
TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
org.apache.ibatis.executor.Executor executor = configuration.newExecutor(tx, execType);
defaultsqlsession = new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx);
throw ExceptionFactory.wrapException(
(new StringBuilder()).append("Error opening session. Cause: ").append(e).toString(), e);
} finally {
ErrorContext.instance().reset();
}
ErrorContext.instance().reset();
return defaultsqlsession;
throw exception;
}
现在已经拿到了session.调用sql代码,事务没问题,提交,有问题,不提交即回滚。操作完毕,关闭session资源。
以上就是对mybatis框架运行原理的文字描述。