Ruchunli's work notes , a good memory is worse than a bad pen
Reprinted from: In Layman mybatis-sqlsession
Creation of Sqlsession
The
sqlsession corresponds to a database session. Because the database session is not permanent, the life cycle of the sqlsession should not be permanent, instead, you need to create it every time you access the database (not to say that SQL can only be executed once in sqlsession, you could do it multiple times, Once the sqlsession is closed, it needs to be recreated). There is only one place to create sqlsession, and that is the Opensession method of Sqlsessionfactory:
Package Org.apache.ibatis.session;import Java.sql.connection;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 ();}
The place to actually create the sqlsession is Opensessionfromdatasource, as follows:
package org.apache.ibatis.session.defaults;import java.sql.connection;import java.sql.sqlexception;import org.apache.ibatis.exceptions.exceptionfactory;import org.apache.ibatis.executor.errorcontext;import org.apache.ibatis.executor.executor;import org.apache.ibatis.mapping.environment;import org.apache.ibatis.session.configuration;import org.apache.ibatis.session.executortype;import org.apache.ibatis.session.sqlsession;import org.apache.ibatis.session.sqlsessionfactory;import org.apache.ibatis.session.transactionisolationlevel; import org.apache.ibatis.transaction.transaction;import org.apache.ibatis.transaction.transactionfactory;import org.apache.ibatis.transaction.managed.managedtransactionfactory;public class defaultsqlsessionfactory implements sqlsessionfactory { private final Configuration configuration; public defaultsqlsessionfactory (ConfIguration configuration) { this.configuration = configuration; } public sqlsession opensession () { return Opensessionfromdatasource (Configuration.getdefaultexecutortype (), null, false); } private sqlsession opensessionfromdatasource (executortype exectype, Transactionisolationlevel level, boolean autocommit) { transaction tx = null; try { final Environment environment = configuration.getenvironment (); Final transactionfactory transactionfactory = gettransactionfactoryfromenvironment ( environment); tx = transactionfactory.newtransaction ( Environment.getdatasource (), level, aUtocommit); final executor executor = Configuration.newexecutor (Tx, exectype, autocommit); return New defaultsqlsession (Configuration, executor); } 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 (); } }}
As you can see, creating sqlsession has been through the following major steps:
1) obtain environmentfrom the configuration;
2) obtain DataSourcefrom the environment ;
3) obtain transactionfactoryfrom the environment ;
4) Get database Connection object from DataSource Connection;
5) Create the transaction object Transaction on the database connection obtained ;
6) create Executor Object (This object is very important, in fact All the operations of sqlsession are done by it) ;
7) Create the sqlsession object.
Creation of executor
Sqlsession is just a façade, the real director is executor,sqlsession operation of the database is done through executor. As with sqlsession, executor is also created dynamically:
Final Executor Executor = Configuration.newexecutor (TX, Exectype, autocommit);
Implementation of the configuration class:
public class configuration { protected environment environment; public executor newexecutor (transaction transaction, executortype Executortype, boolean autocommit) { executorType = executortype == null ? defaultexecutortype : executortype; executorType = executorType == null ? ExecutorType.SIMPLE : executortype; executor executor; if ( Executortype.batch == executortype) { executor = New batchexecutor (this, transaction); } else if ( Executortype.reuse == executortype) { executor = New reuseexecutor (this, transaction); &nBSP;} else { executor = new simpleexecutor (this, Transaction); } if (cacheenabled) { executor = new cachingexecutor (Executor, autocommit); } executor = (Executor) interceptorchain.pluginall (executor); return executor; } }
Definition of
Executor:
Package org.apache.ibatis.executor;import java.sql.sqlexception;import java.util.list;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.mapping.BoundSql;import org.apache.ibatis.mapping.mappedstatement;import org.apache.ibatis.reflection.metaobject;import org.apache.ibatis.session.resulthandler;import org.apache.ibatis.session.rowbounds;import Org.apache.ibatis.transaction.transaction;public interface executor { resulthandler no_result_handler = null; int update (Mappedstatement ms, object parameter) throws sqlexception; <e> list<e> query ( mappedstatement ms, object parameter, rowbounds rowbounds, resulthandler Resulthandler, cachekey cachekey, boundsql boundsql) throws SQLException; <e> list<e> query (MappedstatemeNt ms, object parameter, rowbounds rowbounds, resulthandler resulthandler) throws sqlexception; list<batchresult> flushstatements () throws Sqlexception; void commit (boolean required) throws SQLException; Void rollback (boolean required) throws SQLException; CacheKey Createcachekey (mappedstatement ms, object parameterobject, rowbounds rowbounds, Boundsql boundsql); boolean iscached (Mappedstatement ms, cachekey key); void clearlocalcache (); void deferload (mappedstatement ms, metaobject resultobject, string property, cachekey key, class<?> TargetType); transaction gettransaction (); void close (boolean Forcerollback); boolean isclosed ();}
650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/8C/C2/wKioL1h3P17iInW1AAAuMO9C85k200.jpg "title=" 20170112163101.jpg "alt=" Wkiol1h3p17iinw1aaaumo9c85k200.jpg "/>
As you can see, the executor created is just one of the basic types in 3:
Batchexecutor dedicated to performing bulk SQL operations
Reuseexecutor will reuse statement to perform SQL operations
Simpleexecutor just simple execution of SQL is nothing special.
If the cache is turned on (the default is on and there is no reason to turn it off), Cachingexecutor is created with the executor created earlier as the unique parameter. Cachingexecutor looks for the cache before querying the database, and calls delegate (the executor object that is constructed when it is built) to query from the database and store the query results in the cache if it is not found.
Package org.apache.ibatis.executor;import java.sql.sqlexception;import java.util.list;import org.apache.ibatis.cache.Cache;import org.apache.ibatis.cache.CacheKey;import org.apache.ibatis.cache.transactionalcachemanager;import org.apache.ibatis.mapping.boundsql;import org.apache.ibatis.mapping.mappedstatement;import org.apache.ibatis.mapping.parametermapping;import org.apache.ibatis.mapping.parametermode;import org.apache.ibatis.mapping.statementtype;import org.apache.ibatis.reflection.metaobject;import org.apache.ibatis.session.resulthandler;import Org.apache.ibatis.session.rowbounds;import org.apache.ibatis.transaction.transaction;public class CachingExecutor implements Executor { private Executor delegate; private boolean autoCommit; // issue #573. no need to call commit () on autocommit sessions private transactionalcachemanager tcm = new Transactionalcachemanager (); private boolean dirty; public Cachingexecutor (executor delegate) { this (delegate, false); } public cachingexecutor (Executor delegate, boolean autocommit) { this.delegate = delegate; this.autoCommit = Autocommit; } public transaction gettransaction () { return delegate.gettransaction (); } public void close (boolean Forcerollback) { try { //issue #499. Unresolved session handling //issue #573 . Autocommit sessions should commit if (Dirty && !autocommit) { tcm.rollback (); } else { tcm.commit (); } } finally { delegate.close (Forcerollback); } } // other code slightly }
Executor objects can be intercepted by plug-ins (interceptor interceptor, such as:
@Intercepts ({@Signature (type = Executor.class, method = "Query",
args = {Mappedstatement.class, object.class, Rowbounds.class, Resulthandler.class})})
), if a plug-in is defined for the executor type, the resulting executor object is the proxy object that is inserted by each plug-in.
Mapper Introduction
The MyBatis official manual recommends accessing MyBatis through Mapper objects, as using mapper looks more elegant, like this:
Session = Sqlsessionfactory.opensession (); Usermapper usermapper= Session.getmapper (usermapper.class); Userbo user = new Userbo (); User.setusername ("Imbatis"); User.setpassword ("Imbatis"); Usermapper.insertuser (user);
So what exactly is this mapper, how it was created, and how does it relate to sqlsession? Here's a solution for you.
On the surface, Mapper is created in sqlsession, but the place where it is actually created is Mapperregistry:
Package org.apache.ibatis.session;import java.io.closeable;import java.sql.connection;import java.util.list;import java.util.map;import org.apache.ibatis.executor.batchresult;/** * The primary Java interface for working with MyBatis. * Through this interface you can execute commands, get mappers and manage transactions. * */public interface SqlSession extends Closeable { <t> t selectone (string statement); <T> T selectone (String statement, object parameter); <e> list<e> selectlist (string statement); <e> list<e> selectlist (String Statement, object parameter); <e> list<e> selectlist (String Statement, object paramEter, rowbounds rowbounds); <k, v> map<k, v> selectmap ( String statement, string mapkey); <k, v> map<k, v> Selectmap (String statement, object parameter, string mapkey); <K, V> map<k, v> selectmap (string statement, object parameter, string mapkey, rowbounds rowbounds); void select (String statement, object parameter, resulthandler handler); void select (String statement, Resulthandler handler); void select (String statement, object parameter, rowbounds rowbounds, resulthandler handler); int insert (String statement); int insert (string statement, object parameter); int update (String statemeNT); int update (string statement, object parameter); int delete (string statement); int delete (String statement, object parameter); void commit (); void commit (Boolean force); void rollback (); void rollback (Boolean force); list<batchresult> flushstatements (); void close (); void clearcache (); configuration GetConfiguration (); <t> t getmapper (Class<t> type); Connection getconnection ();}
This article is from the "world of Stuffy Gourd" blog, please be sure to keep this source http://luchunli.blog.51cto.com/2368057/1891463
Introduction to the sqlsession of MyBatis