openSession()的底层执行流程
1. sqlSession
// 将SqlSessionFactory这个复杂对象的创建交由Builder来执行 [使用了创建者模式]
// 根据xml配置文件(mybatis-config.xml全局配置文件)创建一个SqlSessionFactory对象[有数据源一些运行环境信息]
String resource = "test/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 1)、根据全局配置文件得到SqlSessionFactory;
// 2)、使用sqlSession工厂,获取到sqlSession对象使用他来执行增删改查
// 2.1 一个sqlSession就是代表和数据库的一次会话,用完关闭
SqlSession sqlSession = sqlSessionFactory.openSession();
...
try {
// 3) 获取接口的实现类对象
// 会为接口自动的创建一个代理对象,代理对象去执行增删改查方法
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
...
sqlSession.commit();
} finally {
sqlSession.close();
}
2. DefaultSqlSessionFactory类
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
public SqlSession openSession() {
// 调用openSessionFromDataSource方法
// openSession() => autoCommit: false 默认值,即不自动提交
// openSession(true); 自动提交
return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);
}
......
}
3. openSessionFromDataSource方法
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
DefaultSqlSession var8;
try {
Environment environment = this.configuration.getEnvironment();
// 去读配置文件,获取事务工厂
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
// 事务工厂创建一个事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 根据传入的事务(Transaction)和执行的类型【SIMPLE,REUSE,BATCH】来拿到一个执行器
Executor executor = this.configuration.newExecutor(tx, execType);
// 通过初始化完成的configuration和executor , 来new一个DefaultSqlSession
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
} catch (Exception var12) {
this.closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);
} finally {
ErrorContext.instance().reset();
}
return var8; // DefaultSqlSession
}
4. Environment & ExecutorType
// package org.apache.ibatis.mapping;
public final class Environment {
private final String id;
private final TransactionFactory transactionFactory;
private final DataSource dataSource;
}
// ExecutorType execType
public enum ExecutorType {
SIMPLE,
REUSE,
BATCH;
private ExecutorType() {
}
}