MyBatis操作的时候跟数据库的每一次连接,都需要创建一个会话,我们用openSession()方法来创建。这个会话里面需要包含一个Executor用来执行 SQL。Executor又要指定事务类型和执行器的类型。
1.创建Transaction(两种方式)
属性 | 产生工厂类 | 产生事务 |
JDBC | JdbcTransactionFactory | JdbcTransaction |
MANAGED | ManagedTransactionFactory | ManagedTransaction |
- 如果配置的是 JDBC,则会使用Connection 对象的 commit()、rollback()、close()管理事务。
- 如果配置成MANAGED,会把事务交给容器来管理,比如 JBOSS,Weblogic。
SqlSession sqlSession = sqlSessionFactory.openSession();
public SqlSession openSession() { //configuration中有默认赋值 protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
<environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments>
2.创建Executor
//ExecutorType是SIMPLE,一共有三种SIMPLE(SimpleExecutor)、REUSE(ReuseExecutor)、BATCH(BatchExecutor) private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { //xml中的development节点 final Environment environment = configuration.getEnvironment(); //type配置的是Jbdc所以生成的是JbdcTransactionFactory工厂类 final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); //Jdbc生成JbdcTransactionFactory生成JbdcTransaction tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); //创建CachingExecutor执行器 final Executor executor = configuration.newExecutor(tx, execType); //创建DefaultSqlSession属性包括 Configuration、Executor对象 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(); } }