[TOC]
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
<!--定义数据库信息,默认使用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); } }