目录
上一章节我们通过xml和代码的方式实现了Mybatis环境的配置。代码方式只是简单介绍下。我们也知道我们大部分情况使用的是xml方式的配置。在实际开发中我们那样开发显然是不合理的。
上章节提到的组件显示不可能每次执行sql都要重新创建的。这样性能上肯定是过不去的。今天我们就来简单聊聊SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession、Mapper这些组件的生命周期吧。
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);
}
}
原文:https://www.cnblogs.com/zhangxinhua/p/11898350.html