In the past has been in the company's well-written framework of the use of MyBatis directly, but also very simple, do not need any thinking, only focus on SQL statements just fine. But it was strange to use the way he realized the process,
Plainly see only in the DAO layer wrote an interface, in the configuration file to write their own SQL, you can give the impression that the interface is automatically instantiated, and then in the service layer invoke the interface instance, complete his data from the database process.
In this curious drive to open the mybatis of the superficial reading. In fact, a period of time to see some of the framework of the code, has been lazy to summarize, now write a little content for their future reference.
The following is a simplest example to open the understanding of the MyBatis, but also in the most vernacular form for their own later forgotten when the reference.
This is a project overview of this article to read the code primer, in this project as the entrance, I believe that interested in research mybatis people, MyBatis have already had some experience in the use of, paste some code below.
Mybatis_config.xml
MyBatis the configuration file that is read at startup time, eventually all the configuration files will be encapsulated in a class called configuration, for later use
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
<environments default= "Development" >
<environment id= "development" >
<transactionmanager type= "JDBC"/>
<datasource type= "Pooled" >
<property name= " Driver "value=" Com.mysql.jdbc.Driver "/>
<property name=" url "value=" Jdbc:mysql://localhost:3306/mybatis "/>
<property name=" username "value=" root "/>
<property name=" password "value=" 123456 "/>
</dataSource>
</environment>
</environments>
<mappers>
< Mapper resource= "Ball.xml"/>
</mappers>
</configuration>
Ball.xml
The SQL statement that is called when the method database accesses data in the interface, each interface method is encapsulated in a mappedstatement
<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--namespace must correspond to interface, ID must be its own method name---
<mapper namespace= "Iplaydao" >
<select id= "Selectball" Parametertype= "string" resulttype= "Ball" >
select ID, name from ball where id = #{id}
</select>
</mapper>
Iplaydao.java
Public interface Iplaydao {public ball
Selectball (String ID);
}
Ball.java
Omit Getter,setter method
public class Ball {
private String ID;
private String name;
}
Demo.java
The main function class, the start of MyBatis is also from here to analyze
Import Java.io.InputStream;
Import org.apache.ibatis.io.Resources;
Import org.apache.ibatis.session.SqlSession;
Import Org.apache.ibatis.session.SqlSessionFactory;
Import Org.apache.ibatis.session.SqlSessionFactoryBuilder;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
public class Demo {private static Logger LOG = Loggerfactory.getlogger (Demo.class);
public static void Main (string[] args) {sqlsession sqlsession = null;
try {sqlsession = Mybatisutil.getsqlsessionfactory (). Opensession ();
Iplaydao play = Sqlsession.getmapper (Iplaydao.class);
Ball ball = Play.selectball ("1");
Log.info ("query result: {}====>{}", Ball.getid (), Ball.getname ());
} finally {sqlsession.close ();
}} static class Mybatisutil {private static sqlsessionfactory sqlsessionfactory = null;
public static Sqlsessionfactory Getsqlsessionfactory () {InputStream inputstream = null;
if (sqlsessionfactory = = null) {try {String resource = "Mybatis_config.xml"; InputStream = Resources.getresourceasstream (Resource);
Sqlsessionfactory = new Sqlsessionfactorybuilder (). Build (InputStream);
return sqlsessionfactory;
} catch (Exception ex) {System.err.println (Ex.getmessage ());
Ex.printstacktrace ();
}} return sqlsessionfactory;
}
}
}
In order to facilitate the process of getting sqlsessionfactory to a static inner class, all the critical code is accumulated in this class.
Basically analyze this process:
(1) First get the parsing configuration file Mybatis_config
(2) MyBatis with a configuration file to build a Sqlsessionfactory object
(3) Open the MyBatis execution process door from sqlsessionfactory, get Sqlsession Object
(4) Call the Getmapper method to pass the interface inside the framework to implement the agent process
(5) Call the interface method, actually took a circle of agent flow inside the mybatsis, finally obtained the result
The following open to MyBatis internal free, the entire process of MyBatis consists of two processes, one is the configuration file read encapsulated as a config process, one is to execute an interface method to implement the entire agent process.
In fact, all frameworks are a process in which the entire framework is initialized based on the configuration file, and then the entire process is implemented in conjunction with each other to complete the interface execution process.
It seems like this has been written down the article is too long, first to summarize the whole process of writing down, the following two articles respectively introduced configuration, and agent execution process, mainly four objects Executor,statementhandler,
Parmeterhandler,resulthandler, by sqlsession, the whole process is perfectly assembled together.
1.getMapper () in the process of the DAO interface implemented a dynamic proxy
2. When the interface calls its internal method, it goes to the Mapperproxy class of the Invoke method in the 3.MapperProxy class to wrap the method into Mappermethod, Then call its Mappermethod's Execute method (where sqlsession is passed as a parameter, in command mode) 4.sqlsession contains a executor actuator, The method called by sqlsession corresponds to internal use of executor to invoke 5. Statementhandler 6 is initialized in the specific method. The Statementhandler initializes the Parameterhandler and Resulthandler after initialization is complete, and is passed into the Preparestatement method as a parameter. Create a true JDBC statement object &NBSP;JDBC |-----------------1. Drivermanage ---------------------------->connection & nbsp | , &NB Sp |createstatement ()---------Statement & nbsp | ----------------2.Connection | | , &NB Sp |preparestatement (SQL)----Prea & nbsp | &N Bsp | &NB Sp | | &NB Sp , &NB Sp | &N Bsp &NBSP | Statement | | &N Bsp |------------------3. | , &NB Sp | &N Bsp &NBSP ; | &N Bsp , &NBSp | Preparestatement / / nbsp | &NBS P | In 8.prepareStatement, the Statement/preparestatementhandler preparation parameters are created with Statementhandler to obtain the result 9. prepare () gets statement== because statement and preparestatement have different times for incoming SQL statements, the internal use of instantiatestatement creates 10. Paramerize () set the parameter (statement the function is empty, mainly for preparestatement preparation) 11.StatementHandler call the specific method (above Mappermethod specific execution of additions and deletions) 12. Statement gets SQL, executes the statement execute method, and then passes statement to the Resulthandler query (or other method), Resulthandler the method internally calls statement Getresutset result set encapsulation. 13.PrepareStatement has set parameters in 9 in the sql,10, so just execute the Execute method, similar to the package structure. Detailed Source Analysis: (1) Parsing configuration filePackage configuration Parsing profiles encapsulated for configuration (2) interface execution process Interface execution flow