我们平时使用db都离不开事务,那在mybatis中是如何实现事务的呢。
mybatis中有事务Transaction,必有生产事务的TransactionFactory。
TransactionFactory:有3个实现类,分别是JdbcTransactionFactory、ManagedTransactionFactory和SpringManagedTransactionFactory,前2者是mybatsi自带的,第3者则是mybatis-spring包中的。前2者都比较简单,本章重点介绍SpringManagedTransactionFactory。
Transaction:也同样有3个实现类,跟上面的Factory相对应,分别是JdbcTransaction、ManagedTransaction和SpringManagedTransaction。
我们接着看,在spring集成mybatis中是如何使用事务的。在解析mybatis-config.xml配置文件的时候,如果没有指定事务工厂,就默认使用SpringManagedTransactionFactory,如下
if (this.transactionFactory == null) {
this.transactionFactory = new SpringManagedTransactionFactory();
}
configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource));
然后在DefaultSqlSessionFactory.openSession时获取事务工厂,生产事务并绑定到Executor,如下
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
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);
return new DefaultSqlSession(configuration, executor, autoCommit);
} 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();
}
}
privat