Mybatis source code analysis introduction to JDBC Mybatis

JDBC process

 Connection conn=null;
 PreparedStatement pstmt=null;
 try {
     // 1. Load drive

     // 2. Create connection SPI
     conn= DriverManager.getConnection("jdbc:mysql://", "db_username", "db_psd");

     // Open transaction

     // SQL statement parameter #{} ${} < if >
     String sql="  select id,user_name,create_time from   t_user where id=?;";

     // Get sql executor:
     // 1. Perform pretreatment

     // Execute query
     ResultSet rs= pstmt.getResultSet();
     //ResultSet rs= pstmt.executeQuery();;
     User user =new User();


     // Commit transaction
 } catch (Exception e) {
     // Rollback transaction
     // close resource
     try {
     } catch (SQLException e) {

JDBC disadvantages

  1. Frequently create database connection objects and release the waste of connection operation resources. Use database connection pool to solve the problem
  2. Hard coding exists in sql statement definition, parameter setting and result set processing. The actual sql development changes greatly and needs to be recompiled and deployed
  3. The parameters passed from prepareStatement to placeholder are hard coded, which may affect maintenance more or less
  4. The result set deals with duplicate codes and is inconvenient to use

ORM(O-Object,R-relational,M-Mapping) Mybatis demo

 String resource = "mybatis-config.xml";
 //Build an XML Configuration file as a Configuration class
 Reader reader = Resources.getResourceAsReader(resource);
 //Build a sqlsessionfactory (parse xml file) by loading the configuration file stream
 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

 // Data source executor (DefaultSqlSession)
 SqlSession session = sqlSessionFactory.openSession();
 try {
     // Execute query (underlying jdbc)
     User user =  session.selectOne("", 1);

     // Create dynamic proxy
    /* UserMapper mapper = session.getMapper(UserMapper.class);
     User user = mapper.selectById(1);*/


 } catch (Exception e) {
 } finally {


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-// Config 3.0//EN"
    <!--properties Scan properties  -->
    <properties resource=""></properties>
        <plugin interceptor="" ></plugin>
    <environments default="development">
        <environment id="development">
           <transactionManager type="JDBC"/>
                mybatis Built in JNDI,POOLED,UNPOOLED Three types of data sources,
                among POOLED The corresponding implementation is org.apache.ibatis.datasource.pooled.PooledDataSource,
                It is mybatis A synchronous and thread safe database connection pool is implemented 
                Generally in production,We will use c3p0 perhaps druid Connection pool
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driverClass}"/>
                <property name="url" value="${mysql.jdbcUrl}"/>
                <property name="username" value="${mysql.user}"/>
                <property name="password" value="${mysql.password}"/>
        <mapper resource="com/mx/mapper/UserMapper.xml"/>
        <!--<package name=""/>-->
        <!--The interface name must be guaranteed (e.g IUserDao)and xml Name( IUserDao.xml)Same, must also be in the same package-->


SqlSessionFactoryBuilder. Build = > xmlconfigbuilder - > xmlmapperbuilder - > xmlstatementbuilder - > xmlscriptbuilder - > dynamicsqlsource dynamic / RawSqlSource static - > sqlsource - (execute) - > boundsql

L1 cache SqlSession BaseExecutor
L2 cache application level cacheingexecution

What are the programming steps of MyBatis?

  1. Create SqlSessionFactory
  2. Create SqlSession through SqlSessionFactory
  3. Perform database operations through SqlSession
  4. Call session Commit() commit transaction
  5. Execute session Close() close the reply

How does MyBatis work?

  1. Read the Mybatis configuration file: Mybatis config XML is the global configuration file of Mybatis, which configures the running environment of Mybatis and the connection pool..
  2. Load mapping file: SQL mapping file, in which the database SQL statement is configured, which needs to be in the Mybatis configuration file Mybatis config XML, Mybatis config Multiple mapping files can be loaded in the XML file, and each file corresponds to the table in the database
  3. Construct callback factory: build session factory SqlSessionFactory through configuration information such as Mybatis environment
  4. Create reply object: create a reply object SqlSession object through the reply factory, which contains all methods of executing Sql
  5. Executor executor: the bottom layer of Mybatis defines an executor interface operation database, dynamically generates the SQL to be executed according to the parameters passed by SqlSession, and is responsible for query cache maintenance (Cache/Base/Simple/Reuse/Batch)
  6. MappedStatement object: the parameter type of the Executor execution method. This parameter encapsulates the mapping information and stores the SQL statement ID and parameter information to be mapped
  7. Input parameter mapping: the input parameter types can be Map,List, etc., as well as basic data types and POJO types. The input parameter mapping process is similar to the setting of prepareStatement parameter object by JDBC
  8. Output result mapping: the output result types can be Map, List, basic data type and POJO type. The output result is similar to the parsing process of JDBC for the result set

MyBatis framework architecture design?

Added by youdontmeanmuch on Mon, 07 Feb 2022 21:13:17 +0200