MyBatis source code analysis - Introduction to MyBatis, open your mouth and come

*   *   [4.1 stay pom.xml Add dependency](about:blank#41_pomxml_276)

    *   [4.2 stay application.yml to configure](about:blank#42_applicationyml_322)

    *   [4.3 mapper file](about:blank#43_mapper_362)

    *   [4.4 Creating user tables and adding user data](about:blank#44__395)

    *   [4.5 Create entity class](about:blank#45__435)

    *   [4.6 newly build dto and vo object](about:blank#46_dtovo_478)

    *   [4.7 bean Conversion tool class](about:blank#47_bean_554)

    *   [4.8 user service Interface](about:blank#48_service_577)

    *   [4.9 user controller](about:blank#49_controller_615)

    *   [4.10 Startup class](about:blank#410__636)

*   [5.summary](about:blank#5_662)

*   [reference resources](about:blank#_670)

|Serial number | content | link|

| — | — | — |

|1 | MyBatis source code analysis - Introduction to MyBatis |[ https://thinkwon.blog.csdn.net/article/details/114808852 ](

) |

|2 | MyBatis source code analysis - configuration file analysis process |[ https://thinkwon.blog.csdn.net/article/details/114808962 ](

) |

|3 | MyBatis source code analysis - mapping file parsing process |[ https://thinkwon.blog.csdn.net/article/details/115423167 ](

) |

|4 | MyBatis source code analysis - SQL execution process |[ https://thinkwon.blog.csdn.net/article/details/115603376 ](

) |

|5 | MyBatis source code analysis - built-in data source |[ https://thinkwon.blog.csdn.net/article/details/116331419 ](

) |

|6 | MyBatis source code analysis - cache principle |[ https://thinkwon.blog.csdn.net/article/details/116809942 ](

) |

|7 | MyBatis source code analysis - plug-in mechanism |[ https://thinkwon.blog.csdn.net/article/details/116809961 ](

) |

[](

)1. A quick overview of this article

This article explains and demonstrates MyBatis from three perspectives: what, why and how.

[](

)2. What is MyBatis

MyBatis, formerly known as iBatis, is an open source project under the Apache Software Foundation. In 2010, the project was moved out of the Apache foundation and renamed MyBatis. In the same period, iBatis stopped maintenance.

MyBatis is a semi-automatic Java persistence framework, which associates objects with SQL through annotations or XML. The reason why it is semi-automatic is because it can automatically generate SQL with some ORM(Object Relational Mapping) such as Hibernate Compared with the framework, using MyBatis requires users to maintain SQL by themselves. Maintaining SQL is cumbersome, but it also has advantages. For example, we can control SQL logic and optimize it to improve efficiency.

MyBatis is an easy-to-use persistence layer framework. Users can master the usage of its common features through simple learning, which is also a reason why MyBatis is widely used.

[](

)3. Why use MyBatis

There is usually no difference between technologies. From the perspective of application scenarios, technologies that meet the needs of application scenarios are the appropriate choice. Next, I will compare the advantages and disadvantages of these database access technologies by writing code, and explain the applicable scenarios of MyBatis at the end.

Here, first post some public classes and configurations used in this chapter

public class Article {

    private Integer id;

    private String title;

    private String author;

    private String content;

    private Date createTime;

    

    // Omit getter/setter and toString

} 

The database related configuration is placed in the jdbc.properties file. The details are as follows:

jdbc.driver=com.mysql.cj.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/coolblog?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE

jdbc.username=root

jdbc.password=**** 

The table records as follows:

The database sql is as follows:

DROP TABLE IF EXISTS `article`;



CREATE TABLE `article` (

  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,

  `author_id` int(11) NOT NULL,

  `title` varchar(32) DEFAULT NULL,

  `type` tinyint(4) DEFAULT NULL,

  `content` text,

  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;



LOCK TABLES `article` WRITE;

/*!40000 ALTER TABLE `article` DISABLE KEYS */;



INSERT INTO `article` (`id`, `author_id`, `title`, `type`, `content`, `create_time`)

VALUES

	(1,1,'MyBatis Introduction to source code analysis series',8,'MyBatis Introduction to source code analysis series','2018-07-15 15:30:09'),

	(2,2,'HashMap Detailed analysis of source code(JDK1.8)',1,'HashMap Detailed analysis of source code(JDK1.8)','2018-01-18 15:29:13'),

	(3,1,'Java CAS Principle analysis',1,'Java CAS Principle analysis','2018-05-15 15:28:33'),

	(4,1,'Spring IOC Container source code analysis - Get singleton bean',4,'Spring IOC Container source code analysis - Get singleton bean','2018-06-01 00:00:00'),

	(5,1,'Spring IOC Container source code analysis - Solution to circular dependency',4,'Spring IOC Container source code analysis - Solution to circular dependency','2018-06-08 00:00:00'),

	(6,2,'Spring AOP Introduction to source code analysis series',4,'Spring AOP Introduction to source code analysis series','2018-06-17 00:00:00'),

	(7,2,'Spring AOP Source code analysis - Create proxy object',4,'Spring AOP Source code analysis - Create proxy object','2018-06-20 00:00:00'),

	(8,1,'Spring MVC Principle Exploration - A requested travel process',4,'Spring MVC Principle Exploration - A requested travel process','2018-06-29 00:00:00'),

	(9,2,'Spring MVC Principle Exploration - Container creation process',4,'Spring MVC Principle Exploration - Container creation process','2018-06-30 00:00:00'),

	(10,2,'Spring IOC Introduction to container source code analysis series',4,'Spring IOC Introduction to container source code analysis series','2018-05-30 00:00:00');



/*!40000 ALTER TABLE `article` ENABLE KEYS */;

UNLOCK TABLES;



# Dump of table author

# ------------------------------------------------------------



DROP TABLE IF EXISTS `author`;



CREATE TABLE `author` (

  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(32) DEFAULT NULL,

  `age` tinyint(4) DEFAULT NULL,

  `sex` tinyint(4) DEFAULT NULL,

  `email` varchar(64) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;



LOCK TABLES `author` WRITE;

/*!40000 ALTER TABLE `author` DISABLE KEYS */;



INSERT INTO `author` (`id`, `name`, `age`, `sex`, `email`)

VALUES

	(1,'coolblog.xyz',28,0,'coolblog.xyz@outlook.com'),

	(2,'nullllun',29,1,'coolblog.xyz@outlook.com');



/*!40000 ALTER TABLE `author` ENABLE KEYS */;

UNLOCK TABLES;



# Dump of table student

# ------------------------------------------------------------



DROP TABLE IF EXISTS `student`;



CREATE TABLE `student` (

  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,

  `name` varchar(32) DEFAULT NULL,

  `age` tinyint(4) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;



LOCK TABLES `student` WRITE;

/*!40000 ALTER TABLE `student` DISABLE KEYS */;



INSERT INTO `student` (`id`, `name`, `age`)

VALUES

	(1,'coolblog',20);



/*!40000 ALTER TABLE `student` ENABLE KEYS */;

UNLOCK TABLES; 

[](

)3.1 accessing the database using MyBatis

As mentioned earlier, MyBatis is a semi-automatic Java persistence framework. Users need to maintain SQL by themselves to use MyBatis. Here, we put the SQL in XML and the file name is ArticleMapper.xml. The relevant configurations are as follows:

<mapper namespace="xyz.coolblog.dao.ArticleDao">

    <resultMap id="articleResult" type="xyz.coolblog.model.Article">

        <id property="id" column="id"/>

        <result property="title" column="title"/>

        <result property="author" column="author"/>

        <result property="content" column="content"/>

        <result property="createTime" column="create_time"/>

    </resultMap>

    

    <select id="findByAuthorAndCreateTime" resultMap="articleResult">

        SELECT

            `id`, `title`, `author`, `content`, `create_time`

        FROM

            `article`

        WHERE

            `author` = #{author} AND `create_time` > #{createTime}

    </select>

</mapper> 

The above SQL is used to query the article records written by an author from a certain time to the present from the article table. In MyBatis, the SQL mapping file needs to correspond to the data access interface. For example, the above configuration corresponds to the xyz.coolblog.dao.ArticleDao interface. The definition of this interface is as follows:

public interface ArticleDao {

    List<Article> findByAuthorAndCreateTime(@Param("author") String author, @Param("createTime") String createTime);

} 

In order for MyBatis to run, some configurations are needed, such as configuring data sources, configuring the location information of SQL mapping files, etc. the configurations used in this section are as follows:

<configuration>

    <properties resource="jdbc.properties"/>



    <environments default="development">

        <environment id="development">

            <transactionManager type="JDBC"/>

            <dataSource type="POOLED">

                <property name="driver" value="${jdbc.driver}"/>

                <property name="url" value="${jdbc.url}"/>

                <property name="username" value="${jdbc.username}"/>

                <property name="password" value="${jdbc.password}"/>

            </dataSource>

        </environment>

    </environments>

    

    <mappers>

        <mapper resource="mapper/ArticleMapper.xml"/>

    </mappers>

</configuration> 

At this point, the environment required by MyBatis is configured. Next, run MyBatis. The relevant test codes are as follows:

public class MyBatisTest {



    private SqlSessionFactory sqlSessionFactory;



    @Before

    public void prepare() throws IOException {

        String resource = "mybatis-config.xml";

        InputStream inputStream = Resources.getResourceAsStream(resource);

        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        inputStream.close();

    }



    @Test

    public void testMyBatis() throws IOException {

        SqlSession session = sqlSessionFactory.openSession();

        try {

            ArticleDao articleDao = session.getMapper(ArticleDao.class);

            List<Article> articles = articleDao.findByAuthorAndCreateTime("coolblog.xyz", "2018-06-10");

        } finally {

            session.commit();

            session.close();

        }

    }

} 

In the above test code, the prepare method is used to create a SqlSessionFactory factory, which is used to create a SqlSession. Through SqlSession, a proxy object can be generated for our database access interface ArticleDao interface. MyBatis will associate the interface method findByAuthorAndCreateTime with the SQL configured in the SQL mapping file, and call this method SQL related to execution.

The running results of the above test code are as follows:

As mentioned above, when learning the MyBatis framework, you can configure the MyBatis log, so that you can print the debugging information of MyBatis to facilitate the observation of the SQL execution process. In the above results, the line where the = = > symbol represents the SQL and related parameters entered into the database. The line where the < = = symbol represents the SQL execution result.

[](

)3.2 introduction to JDBC and Spring JDBC

JDBC

As the database access specification of the Java platform, JDBC only provides one ability to access the database. Use steps: load the database driver, create the database connection object, create the SQL execution statement object, execute SQL and process the result set. Disadvantages: JDBC process is cumbersome; splicing SQL may lead to SQL errors; mixing SQL and Java code will reduce the generation The readability of the code is not conducive to maintenance; the processing of execution results is troublesome; the user also needs to manually manage the database connection and manually obtain the database connection at the beginning. After using it, the database connection must be closed manually

Spring JDBC

Spring JDBC has been thinly packaged on the basis of JDBC, and its ease of use has been greatly improved. However, it also has some defects. For example, SQL is still written in code, and users need to handle the ResultSet by themselves. However, compared with JDBC, spring JDBC does not need to manually load database drivers, obtain database connections, and create Statement objects In general, ease of use has been greatly improved.

[](

)3.3 comparison between mybatis and Hibernate

MyBatis and Hibernate have something in common: they are both the encapsulation of jdbc, the framework of persistence layer and the development of dao layer.

| | MyBatis | Hibernate |

| — | — | — |

|Mapping relationship | configure the corresponding relationship between Java objects and sql statement execution results. The configuration of multi table association relationship is simple | configure the corresponding relationship between Java objects and database tables. The configuration of multi table association relationship is complex|

|SQL optimization and portability | MyBatis needs to manually write SQL, support dynamic SQL, process lists, dynamically generate table names, and support stored procedures. The development workload is relatively large. Directly using SQL statements to operate the database does not support database independence, but SQL statements are easy to optimize| Hibernate encapsulates SQL statements and provides logging, caching, cascading (cascading is more powerful than MyBatis). In addition, it also provides HQL (Hibernate Query Language) to operate the database. It has good database independence support, but it will consume more performance. If the project needs to support multiple databases, the amount of code development is small, but SQL statement optimization is difficult|

|Learning cost | MyBatis is a lightweight framework with low learning and use threshold | Hibernate is a heavyweight framework with high learning and use threshold|

|Usage scenario | suitable for large projects with frequent demand changes, such as Internet e-commerce system | suitable for small and medium-sized projects with relatively stable demand, such as office automation system|

|Summary | MyBatis is a compact, convenient, efficient, simple, direct and semi-automatic persistence layer framework | Hibernate is a powerful, convenient, efficient, complex, indirect and fully automated persistence layer framework|

[](

)4. How to use MyBatis

The main ways to use MyBatis are: use MyBatis alone, integrate with Spring, and integrate with Spring Boot. In view of the current popularity of using Spring Boot, the next step is to introduce the integrated use of MyBatis and Spring Boot. Readers interested in the other two methods can try them by themselves.

[](

)4.1 add dependency in pom.xml

<dependencies>

    <!-- mybatis -->

    <dependency>

        <groupId>org.mybatis.spring.boot</groupId>

        <artifactId>mybatis-spring-boot-starter</artifactId>

        <version>2.1.4</version>

    </dependency>



    <!-- mysql Database driven -->

    <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

        <scope>runtime</scope>

    </dependency>



    <!-- lombok -->

    <dependency>

        <groupId>org.projectlombok</groupId>

        <artifactId>lombok</artifactId>

        <optional>true</optional>

    </dependency>



    <!-- springboot 2.3.0 And above@Validated @Valid Problems that don't work -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-validation</artifactId>

    </dependency>



    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>



    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies> 

[](

)4.2 configure in application.yml

# Application service WEB access port

server:

  port: 8080



# spring configuration

spring:

  application:

    name: spring-boot-mybatis

  # Database configuration


Tags: Java Hibernate SQL Back-end Programmer

Posted on Thu, 09 Sep 2021 19:42:05 -0400 by mrfritz379