给自己的每日一句
不从恶人的计谋,不站罪人的道路,不坐亵慢人的座位,惟喜爱耶和华的律法,昼夜思想,这人便为有福!他要像一棵树栽在溪水旁,按时候结果子,叶子也不枯干。凡他所做的尽都顺利
前言
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();
作为一个开发界的菜鸟,当我研究Mybatis的源码的时候,总是好奇,上边这三行代码单当中走过的时候,发生了什么样的事情呢?我们这篇文章只研究openSession这个方法。
sqlSessionFactory.openSession()
public interface SqlSessionFactory {SqlSession openSession();SqlSession openSession(boolean autoCommit);SqlSession openSession(Connection connection);SqlSession openSession(TransactionIsolationLevel level);SqlSession openSession(ExecutorType execType);SqlSession openSession(ExecutorType execType, boolean autoCommit);SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);SqlSession openSession(ExecutorType execType, Connection connection);Configuration getConfiguration();}
SqlSessionFactory是SqlSession的工厂,各种各样的重载的openSession方法。
实现类有两个,默认走的都是第一个DefaultSqlSessionFactory
@Overridepublic SqlSession openSession() {return openSessionFromDataSource(//默认的是SimpleExcutor,configuration.getDefaultExecutorType(), null, false);}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {Transaction tx = null;try {//final可以修饰局部变量//获取Mybatis-config.xml中的Environment标签对应的对象final Environment environment = configuration.getEnvironment();//通过environment获取事务工厂final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);//通过事务工厂和数据源获取事务对象tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);//configuration.newExecutor(事务对象,Executor类型对象)final Executor executor = configuration.newExecutor(tx, execType);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();}}
通过Environment 获取TransactionFactory 对象
通过TransactionFactory和Environment中的DateSource获取Transaction
通过Transaction 和 ExcutorType获取 Executor 对象
通过Executor configuration autoCommit获取SqlSession对象、
我们可以得出以下结论
1:openSession()默认创建的是DefaultSqlSession对象,而且三个入参是:ExcutorType、TransatinIsolationLevel、AutoCommit
2:默认的Exuecutor是SimpleExecutor
3:Excutor对象是由Configuration创建的,默认void:SimpleExcutor,param:Transaction、ExecutorType