• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

MyBatis openSession(),close(),和commit()用法解释

mybatis 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论

一:MyBatis工具类 中openSession到底做了什么?

Mybatis工具类

 1     private static final String RESOURCE = "mybatis-config.xml"; 2     private static SqlSessionFactory sqlSessionFactory = null; 3     private static ThreadLocal<SqlSession> thr<strong style="color:transparent">本文来源gaodai#ma#com搞@@代~&码*网/</strong>eadLocal = new ThreadLocal<SqlSession>(); 4  5  6  7  8     //关闭sqlsession 9     public static void closeSession(){10         SqlSession session = (SqlSession) threadLocal.get(); // 211         threadLocal.set(null);12         if (session !=null){13             session.close();14         }15     }16 17     public static SqlSession getSessionTwo() {18         //读取配置文件19         try {20             InputStream stream = Resources.getResourceAsStream(RESOURCE);21             sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);22 23             return sqlSessionFactory.openSession();   //返回openSession24         } catch (IOException e) {25             e.printStackTrace();26         }27 28         return null;29     }

首先点开openSession 发现踏实sqlsessionFactory的一个方法

 1 package org.apache.ibatis.session; 2  3 import java.sql.Connection; 4  5 public interface SqlSessionFactory { 6     SqlSession openSession(); 7  8     SqlSession openSession(boolean var1); 9 10     SqlSession openSession(Connection var1);

然后再看这 个方法的实现类DefaultSqlSessionFactory

这里主要返回他自己类的一个方法openSessionFroDataSource() (数据源) 并赋值 autoCommit 为false

然后 进入这个方法

 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);            Executor executor = this.configuration.newExecutor(tx, execType);            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;    }
<br />
可以看到他这个方法主要是初始化一些configure.xml的配置信息和DefaultSqlSession
configure.xml的配置信息和DefaultSqlSession

二:MyBatis工具类 中sqlSession.close()底层为什么回滚事务?

首先进入 close()找到他的实现类DefaultsqlSession

DefaultsqlSession里的close方法

<span style="color: #000000">session.close(); 底层为什么可以回滚事务?????<br />DefaultsqlSession里的close方法<br /></span>
 public void close() {try {this.executor.close(this.isCommitOrRollbackRequired(false));this.dirty = false;        } finally {            ErrorContext.instance().reset();        }    }
<span style="color: #000000">     进入Executor接口  查看他的实现类BaseExecutor 找到close()方法<br /></span>
public void close(boolean forceRollback) {   //需要传入一个boolean参数try {try {this.rollback(forceRollback);   //为true则rollback            } finally {if(this.transaction != null) {   this.transaction.close();                }            }        } catch (SQLException var11) {            log.warn("Unexpected exception on closing transaction.  Cause: " + var11);        } finally {this.transaction = null;this.deferredLoads = null;this.localCache = null;this.localOutputParameterCache = null;this.closed = true;        }    }
然后再看下executor.close()里的参数
.executor.close(.isCommitOrRollbackRequired(------>  isCommitOrRollbackRequired(  ||
forceRollback为true 然后进入rollback(forceRollBack)参数为true看下最终的rollback方法  
public void rollback(boolean required) throws SQLException {    if(!this.closed) {        try {            this.clearLocalCache();            this.flushStatements(true);        } finally {            if(required) {                this.transaction.rollback();   //如果传入的参数为 true     则进行事务 回滚            }        }    }
 <br />
<br />

另外至于为什么没有提交之前close会回滚事务,提交了之后则是关闭事务

主要在于Executor的实现类BaseExecutor的

isCommitOrRollbackRequired()参数改变了。

session.commit(); 为什么能提交事务,他的实现和close()的实先基本差不多,主要是

isCommitOrRollbackRequired()方法

参数的真假,真则提交,假便关闭
session会话

000000000写的好low啊自嘲

以上就是MyBatis openSession(),close(),和commit()用法解释的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:MyBatis openSession(),close(),和commit()用法解释

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址