MyBatis openSession (), close (), and commit () underlying code profiling, mybatisopensession

Source: Internet
Author: User

MyBatis openSession (), close (), and commit () underlying code profiling, mybatisopensession

I. What did openSession do in the MyBatis tool class?

Mybatis tool class

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 // close 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 // read the configuration file 19 try {20 InputStream stream = Resources. getResourceAsStream (RESOURCE); 21 sqlSessionFactory = new SqlSessionFactoryBuilder (). build (stream); 22 23 return sqlSessionFactory. openSession (); // returns openSession24} catch (IOException e) {25 e. printStackTrace (); 26} 27 28 return null; 29}

First, open openSession to find a method for implementing 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);

 

Then let's look at the implementation class defasqlsqlsessionfactory of this method.

Here we mainly return a method of his own class openSessionFroDataSource () (data source) and assign the value autoCommit to false.

Then enter this method

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

 

 
We can see that this method mainly initializes configuration information of configure. xml and DefaultSqlSession.

Therefore, openSession Initialization is the main function.
Configure. xml configuration information and DefaultSqlSession

Ii. Why is the underlying transaction rollback of sqlSession. close () in the MyBatis tool?

First, go to close () and find his implementation class defasqlsqlsession.

The close method in defasqlsqlsession

 

  

Session. close (); why can transactions be rolled back at the underlying layer ?????
The close method in defasqlsqlsession
 public void close() {        try {            this.executor.close(this.isCommitOrRollbackRequired(false));            this.dirty = false;        } finally {            ErrorContext.instance().reset();        }    }
Go to the Executor interface to view its implementation class BaseExecutor and find the close () method.
Public void close (boolean forceRollback) {// you need to input a boolean parameter try {this. rollback (forceRollback); // if it is 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 ;}}
Then let's look at the parameters in executor. close ().
This.exe cutor. close (this. isCommitOrRollbackRequired (false); ------> isCommitOrRollbackRequired private boolean isCommitOrRollbackRequired (boolean force) {return true | false ;}
// If close () is called before submission, isComitOrRollbackRequired () returns true.
Then the close () method of the implementation class BaseExecutor of Executor is the parameter
ForceRollback is true, and then the rollback (forceRollBack) parameter is true.
Check the final rollback method.
Public void rollback (boolean required) throws SQLException {
If (! This. closed ){
Try {
This. clearLocalCache ();
This. flushStatements (true );
} Finally {
If (required ){
This. transaction. rollback (); // If the input parameter is true, transaction rollback is performed.
}

}
}
 
 

 

In addition, as to why the transaction is rolled back before the transaction is committed, the transaction is closed after the transaction is committed.

Mainly lies in the implementation class BaseExecutor of Executor

The isCommitOrRollbackRequired () parameter is changed.

3. commit ()

Session. commit (); why can I commit a transaction? Its implementation is basically the same as that of close (), mainly

IsCommitOrRollbackRequired () method

The parameter is true or false. If it is true, it is submitted. If it is false, it is disabled.
Session




000000000 write well, low, self-ridicule




 

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.