目录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); } }
加入战队数据库