01.openSession到底做了什么
1.1 SqlSessionFactory 接口的方法,得找接口的实现类
1.2DefaultSqlSessionFactory implements SqlSessionFactory
进而找到了DefaultSqlSessionFactory 的openSession(),openSession方法的原型如下:
public SqlSession openSession() { return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false); }
1.3openSessionFromDataSource方法原型如下:
private
SqlSession openSessionFromDataSource(ExecutorTypeexecType, TransactionIsolationLevel level,
boolean
autoCommit){
Transaction tx =
null
;
DefaultSqlSession var8; try { Environment e = this.configuration.getEnvironment(); TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(e); tx = transactionFactory.newTransaction(e.getDataSource(), level, autoCommit); Executor executor = this.configuration.newExecutor(tx, execType, autoCommit); var8 = new DefaultSqlSession(this.configuration, executor); } catch (Exception var12) { this.closeTransaction(tx); throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12); } finally { ErrorContext.instance().reset(); } return var8; }
1.4DefaultSqlSession方法原型如下
public DefaultSqlSession(Configuration configuration, Executor executor) { this.configuration = configuration; this.executor = executor; this.dirty = false; }
02.insert和delete底层到底是什么?
Session.insert(“xxx”)
public int insert(String statement) { return this.insert(statement, (Object)null);//调度2个参数的insert } public int insert(String statement, Object parameter) { return this.update(statement, parameter);//底层调用update }
03.为什么session.commit()引起事务的提交?
session.commit();
最终调度到事务的commit
this.transaction.commit();
04.session.close()为什么可以回滚事务
1.从session.insert()开始
public int insert(String statement, Objectparameter) {
return this.update(statement, parameter);
}
—>update
publicint update(String statement, Object parameter) {
this.dirty = true;//注意这里将dirty设置成真,内存数据和DB数据库数据不一致
MappedStatement e = this.configuration.getMappedStatement(statement);
}
session.close()
this.executor.close(this.isCommitOrRollbackRequired(false));
——>isCommitOrRollbackRequired
privateboolean isCommitOrRollbackRequired(boolean force) {
return this.dirty || force; //这里得到的是true
}
——>Executor的close()
public void close(boolean forceRollback) {
this.rollback(forceRollback);//true
}
——>rollback
public void rollback(boolean required)throws SQLException {
if(required) {
this.transaction.rollback();
}
}