注: Mybatis版本是3.5.0。java
Mybatis的DefaultSqlSession是怎麼從DataSource得到Connection的呢?數據庫
先來看下openSessionFromDataSource方法,由於DefaultSqlSession的實例化就是從這個方法中開始的,如List-1所示。session
List-1 DefaultSqlSessionFactory的openSessionFromDataSource方法fetch
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(); } }
以下List-2所示,實例化一個Transaction,傳入的是個dataSource。這個tx是Executor的一個屬性,而Executor又是DefautSqlSession的一個屬性。code
List-2 實例化一個Transactionblog
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
List-2中獲取的Transaction是一個JdbcTransaction,下面咱們來看經過DefaultSqlSession來查詢數據庫的時序圖,get
圖1 使用SimpleExecutor時,查詢的時序圖it
從圖1能夠看出,DefaultSqlSession直到查詢時纔會從DataSource中取出Connection,步驟5。有點相似Lazy initialization的思想。io
一個SqlSession中,若是這個SqlSession含有了一個Connection,那麼該SqlSession中後續對數據庫的操做都使用這個Connection。class