Heim  >  Artikel  >  Java  >  Erläuterung der Verwendung von MyBatis openSession(), close() und commit()

Erläuterung der Verwendung von MyBatis openSession(), close() und commit()

巴扎黑
巴扎黑Original
2017-07-24 15:56:174685Durchsuche

1: Was genau macht openSession in der MyBatis-Toolklasse?

Mybatis-Toolklasse

 1     private static final String RESOURCE = "mybatis-config.xml"; 2     private static SqlSessionFactory sqlSessionFactory = null; 3     private static ThreadLocal<SqlSession> threadLocal = 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     }

Klicken Sie zuerst auf openSession und finden Sie eine Möglichkeit, sqlsessionFactory zu verwenden

 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);

Dann schauen Sie sich die Implementierungsklasse dieser Methode DefaultSqlSessionFactory an

Hier gibt es hauptsächlich eine Methode seiner eigenen Klasse openSessionFroDataSource() (Datenquelle) zurück ) und weist einen Wert zu, autoCommit is false

und geben Sie dann diese Methode ein

 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

2: MyBatis-Tool Warum setzt die zugrunde liegende Schicht von sqlSession.close() in der Klasse die Transaktion zurück?

Geben Sie zuerst close() ein, um die Implementierungsklasse DefaultsqlSession zu finden

Die Close-Methode in DefaultsqlSession

 

session.close(); 底层为什么可以回滚事务?????<br>DefaultsqlSession里的close方法<br>
 public void close() {try {this.executor.close(this.isCommitOrRollbackRequired(false));this.dirty = false;
        } finally {
            ErrorContext.instance().reset();
        }

    }
    
 进入Executor接口  查看他的实现类BaseExecutor 找到close()方法<br>
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>

Außerdem, warum beim Schließen die vorherige Transaktion rückgängig gemacht wird Wird übermittelt, wird die Transaktion geschlossen.

liegt hauptsächlich in der Implementierungsklasse BaseExecutor von Executor

isCommitOrRollbackRequired()参数改变了。

session.commit (); Warum kann die Transaktion übermittelt werden? Die Implementierung ist grundsätzlich dieselbe wie die Implementierung von close(), hauptsächlich

isCommitOrRollbackRequired()方法

Die Parameter sind wahr oder falsch, wahr wird übermittelt, false wird geschlossen <br>Sitzungssitzung



000000000写的好low啊自嘲

Das obige ist der detaillierte Inhalt vonErläuterung der Verwendung von MyBatis openSession(), close() und commit(). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn