MyBatis Series (10)---SQL Execution process analysis (source code)

Source: Internet
Author: User

Original address: http://www.cnblogs.com/dongying/p/4142476.html

Recently too busy, have no time to continue to update the blog, today to continue my mybatis learning journey. In the first nine articles, introduced the configuration and use of MyBatis, then this article will go into the MyBatis source code, analysis of MyBatis implementation process, OK, I do not like the words of saliva, or directly on the work:

1. Sqlsessionfactory and sqlsession.

Through the previous chapters on the introduction and use of mybatis, everyone can appreciate the importance of sqlsession, yes, on the surface, we are all through the sqlsession to execute the SQL statement (note: From the surface, the actual will be said later). So let's start by looking at how to get sqlsession:

(1) First, sqlsessionfactorybuilder to read the MyBatis configuration file and build a defaultsqlsessionfactory. The source code is as follows:

/** * A series of construction methods will eventually call this method (this method is called when the configuration file is reader, and a InputStream method corresponds to this) * @param reader * @param environment * @param prop Erties * @return*/PublicSqlsessionfactory Build (Reader Reader, String environment, properties properties) {Try{//With Xmlconfigbuilder parsing the configuration file, the parsed configuration-related information is encapsulated as a configuration object Xmlconfigbuilder parser =NewXmlconfigbuilder (reader, Environment, properties);//Create a Defaultsessionfactory object hereReturnBuild (Parser.parse ()); }Catch(Exception e) {Throw Exceptionfactory.wrapexception ( "error building Sqlsession." , E); } finally {errorcontext.instance (). reset (); try {reader.close ();} catch (IOException e) { intentionally ignore. Prefer previous error. }}} publicreturn  New Defaultsqlsessionfactory (config);}        

(2) When we get to sqlsessionfactory, we can get the Sqlsession object through Sqlsessionfactory. The source code is as follows:

/*** Usually a series of opensession methods will eventually call this method *@paramExectype *@paramLevel *@paramAutocommit *@return*/Private sqlsession Opensessionfromdatasource (Executortype exectype, transactionisolationlevel level,Booleanautocommit) {Transaction tx =Null;Try{//Confuguration object to get mybatis related configuration information, Environment object contains the configuration of data source and transactionFinal Environment Environment =Configuration.getenvironment ();Final Transactionfactory transactionfactory =Gettransactionfactoryfromenvironment (Environment); tx =Transactionfactory.newtransaction (Environment.getdatasource (), level, autocommit);//Previously said, from the surface, we are using sqlsession in the execution of SQL statements, actually, is actually executed through Excutor, Excutor is the encapsulation of statementfinal Executor Executor = Configuration.newexecutor (tx , Exectype); // key look here, create a Defaultsqlsession object return new defaultsqlsession (configuration, executor , autocommit); } 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 ();}}   

Through the above steps, we have already got the Sqlsession object. The next thing to do is what to do (and, of course, execute the SQL statement). Look at the above, we also recall the previous written demo,

Null;  String resource = "Mybatis-conf.xml";  try {     //newcatch
Get sqlsession through Sqlsessionfactory
Sqlsession sqlsession = Sessionfactory.opensession ();

It's a real thing, isn't it?

Sqlsession we've got it, we can call sqlsession in a series of select ..., insert ..., update ..., delete ... method to make CRUD operations easy and effortless. That's it?  So where's the mapping file we've been configuring? Don't worry, let's keep looking down:

2. Mapperproxy of Sharp Weapon:

In MyBatis, through the mapperproxy dynamic agent of our DAO, that is, when we execute their own written DAO inside the method, is actually the corresponding mapperproxy in the agent. So, let's see how to get the Mapperproxy object:

(1) obtained from the configuration by sqlsession. The source code is as follows:

/**   * Do nothing, go directly to the configuration to find, brother is so capricious   * *  @Override public  <T> T getmapper ( Class<t>this);}     

(2) Sqlsession the burden to the configuration, then look at the configuration. The source code is as follows:

/**   * Hot potato, I do not, you find Mapperregistry to   @param type   @param public<T> T Getmapper ( Class<t>return mapperregistry.getmapper (type, sqlsession);}      

(3) configuration do not this hot potato, and then dumped to the mapperregistry, then we look at Mapperregistry. The source code is as follows:

/*** The net let me do, no, there is no one, I do not do who to do *@paramType *@paramSqlsession *@return*/@SuppressWarnings ("Unchecked")Public <T> T Getmapper (class<t>Type, sqlsession sqlsession) {//Can lazy of lazy, I put the menial hand to mapperproxyfactory to doFinal mapperproxyfactory<t> mapperproxyfactory = (mapperproxyfactory<t>if (mapperproxyfactory = = null new Bindingexception ("type" + Type + "is not known to the Mapperregistry.") ); } try {// key here return Mapperproxyfactory.newinstance ( sqlsession); } catch (Exception e) {new bindingexception ("Error getting mapper instance. Cause: "+ E, e);}           

(4) Mapperproxyfactory was a bitter B man, and the menial work was finally given to him. Let's look at the source code:

/*** People abuse me times, I treat others like first love *@paramMapperproxy *@return*/@SuppressWarnings ("Unchecked") protected T newinstance (mapperproxy<t> mapperproxy) { // Dynamic Proxy We write the DAO interface return (T) Proxy.newproxyinstance (Mapperinterface.getclassloader (), new class[] {mapperinterface}, mapperproxy);} public T newinstance (sqlsession sqlsession) { final mapperproxy<t> mapperproxy = new Mapperproxy <T>(sqlsession, Mapperinterface, Methodcache); return newinstance (mapperproxy);}              

With the above dynamic agent, we can easily use the DAO interface, as we have written before the demo:

Userdao usermapper = Sqlsession.getmapper (Userdao.  Class);   new User ();  

This is more convenient, oh, looks like the source of MyBatis is such a thing ah.

Don't worry, it's not over yet, we haven't seen how the SQL statements are executed.

3. Excutor:

Next, we have to really see the SQL implementation process.

Above, we get the mapperproxy, each mapperproxy corresponds to a DAO interface, then when we use, how does Mapperproxy do? The Source:

Mapperproxy:

/*** This method is triggered when the mapperproxy is executed*/@Overridepublic object invoke (object proxy, Method method, object[] args)ThrowsThrowable {if (Object. Class.equals (Method.getdeclaringclass ()) {try {return Method.invoke (this catch (Throwable t) { exceptionutil.unwrapthrowable (t);}} final mappermethod mappermethod = Cachedmappermethod ( method); // Apart, mainly to mappermethod himself to tube return Mappermethod.execute (sqlsession, args);   

Mappermethod:

View Code

Now that we have returned to sqlsession, then we will look at the sqlsession crud method, in order to save trouble, or choose one of the methods to do analysis. Here, we chose the SelectList method:

Public <E> list<e> SelectList (String statement, Object parameter, rowbounds rowbounds) {try {mappedstatement ms =//crud is actually handed to Excetor to deal with, Excutor actually just wore a vest, sample, Don't think I don't know you wearing a vest! return Executor.query (MS, wrapcollection (parameter), Rowbounds, Executor.no_result_handler); } catch (Exception e) { E, e);} finally {errorcontext.instance (). reset ();}}   

Then, through a layer of calls, will eventually come to the Doquery method, here we will find a excutor to see the implementation of Doquery method, I have chosen simpleexecutor:

Public <E> list<e> Doquery (mappedstatement MS, Object parameter, rowbounds rowbounds, Resulthandler Resulthandler, Boundsql Boundsql)throws SQLException {Statement stmt = nulltry Ms.getconfiguration (); Statementhandler handler = Configuration.newstatementhandler (wrapper, MS, parameter, Rowbounds, Resulthandler, Boundsql); stmt = Preparestatement (handler, Ms.getstatementlog ()); //return handler.<e>query (stmt, Resulthandler ); } finally   

Next, let's look at an implementation class Preparedstatementhandler for Statementhandler (which is also our most common, encapsulated PreparedStatement), Let's see how it's handled:

Throws SQLException {     // to this, the true colors, PreparedStatement, this everybody has memorized now    preparedstatement PS =// return resultsethandler.<e> handleresultsets (PS);}     

At this time, the execution process of SQL is finished. I'm only here to suggest that interested to see the source of Mybatis3.

Well, this is the end of this time, recently too busy, and should be busy.

Original address: http://www.cnblogs.com/dongying/p/4142476.html

MyBatis Series (10)---SQL Execution process analysis (source code)

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.