Mybatis source code analysis introduction to JDBC Mybatis

JDBC process

 Connection conn=null;
 
 PreparedStatement pstmt=null;
 try {
     // 1. Load drive
     Class.forName("com.mysql.jdbc.Driver");

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

     // Open transaction
     conn.setAutoCommit(false);

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

     // Get sql executor:
     // 1. Perform pretreatment
     pstmt=conn.prepareStatement(sql);
     pstmt.setInt(1,1);

     // Execute query
     pstmt.execute();
     ResultSet rs= pstmt.getResultSet();
     //ResultSet rs= pstmt.executeQuery();

     rs.next();
     User user =new User();
     user.setId(rs.getLong("id"));
     user.setUserName(rs.getString("user_name"));
     user.setCreateTime(rs.getDate("create_time"));
     System.out.println(user.toString());

     pstmt=conn.prepareStatement(sql);
     pstmt.setInt(1,1);

     // Commit transaction
     conn.commit();
 } catch (Exception e) {
     e.printStackTrace();
     // Rollback transaction
     conn.rollback();
 }
 finally{
     // close resource
     try {
         if(conn!=null){
             conn.close();
         }
         if(pstmt!=null){
             pstmt.close();
         }
     } catch (SQLException e) {
         e.printStackTrace();
     }
 }

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("com.mx.mapper.UserMapper.selectById", 1);

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

     System.out.println(user.getUserName());

     session.commit();
 } catch (Exception e) {
     e.printStackTrace();
     session.rollback();
 } finally {
     session.close();
 }

mybatis-config.xml

<?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>
    <!--properties Scan properties file.properties  -->
    <properties resource="db.properties"></properties>
    
    <plugins>
        <plugin interceptor="com.mx.plugins.ExamplePlugin" ></plugin>
    </plugins>
    <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}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/mx/mapper/UserMapper.xml"/>
        <!--<package name="com.mx.mapper"/>-->
        <!--The interface name must be guaranteed (e.g IUserDao)and xml Name( IUserDao.xml)Same, must also be in the same package-->
    </mappers>
</configuration>

db.properties

mysql.driverClass=com.mysql.jdbc.Driver
mysql.jdbcUrl=jdbc:mysql://mysql.host:3306/db_mx?characterEncoding=utf8
mysql.user=db_usernam
mysql.password=db_psd

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