目錄java
上一章節咱們經過xml和代碼的方式實現了Mybatis環境的配置。代碼方式只是簡單介紹下。咱們也知道咱們大部分狀況使用的是xml方式的配置。在實際開發中咱們那樣開發顯然是不合理的。spring
上章節提到的組件顯示不可能每次執行sql都要從新建立的。這樣性能上確定是過不去的。今天咱們就來簡單聊聊SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession、Mapper這些組件的生命週期吧。sql
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) { try { XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties); return build(parser.parse()); } catch (Exception e) { throw ExceptionFactory.wrapException("Error building SqlSession.", e); } finally { ErrorContext.instance().reset(); try { inputStream.close(); } catch (IOException e) { // Intentionally ignore. Prefer previous error. } } }
DefaultSqlSessionFactory
。 以鏈接池的角度看待咱們不難推斷出SqlSessionFactory應該是個單例 。SqlSessionFactory對應的是數據庫。一個數據庫原則上應該對應一個SqlSessionFactory來管理。這點在Spring中正好無縫鏈接。把SqlSessionFactory交由spring管理。spring默認是單例模式bean.<!--定義數據庫信息,默認使用development數據庫構建環境--> <environments default="development"> <environment id="development"> <!--jdbc事物管理--> <transactionManager type="JDBC"></transactionManager> <!--配置數據庫鏈接信息--> <dataSource type="POOLED"> <property name="driver" value="${database.driver}"/> <property name="url" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </dataSource> </environment> </environments>
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { //定義一個事物對象 Transaction tx = null; try { //經過配置對象獲取事先配置好的環境對象 這裏對應了xml中的environments標籤 。environments默認develop.因此是develop的environment final Environment environment = configuration.getEnvironment(); //經過環境獲取事物。在environment裏配置了JDBC類型的事物==JdbcTransactionFactory;若是沒有配置則默認採用ManagedTransactionFactory final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); //構建事物對象 , 實際就是屬性的賦值 tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); //獲取執行器 BatchExecutor、ReuseExecutor、SimpleExecutor , 選擇SimpleExecutor //由於默認有緩存,這裏會用CachingExecutor包裹原始Executor , 以後會加載各類插件 final Executor executor = configuration.newExecutor(tx, execType); //返回DefaultSqlSession。寫死 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(); } }
public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); } }
加入戰隊數據庫