SqlSessionFactory接口中聲明了一系列opensession方法,用來返回SqlSession對象。
而DefaultSqlSessionFactory是他的實現類,實現了其中的方法。
如下:
public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
其中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); 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(); } }
傳入的第一個參數為configuration中執行器類型(有三種,SimpleExecutor,BatchExecutor,ReuseExecutor),第二個參數為事物管理等級,第三個是是否自動提交事物。
在方法中的操作:獲取environment對象(全局xml文件中配置)
通過TransactionFactory工廠創建事物對象
創建Executor對象,需要傳入事物對象、environment對象,以及autoCommit。
最后創建並返回SqlSession的實現類的對象,並將其需要的參數傳入。