Why does MyBatis conquer SpringBoot?

1. Advantages of MyBatis

As we all know, MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. By mapping xml to the interface, developers can easily map, parse, and execute SQL in xml by using the interface. MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval of result sets. The purpose of this is to reduce the degree of code coupling, which greatly simplifies common operations in database operations, makes it easier to modify SQL, and makes the code clearer and easier to maintain.

Take a brief look at the advantages of MyBatis to understand why it is integrated into Spring:

1) High flexibility

MyBatis allows direct writing of native SQL statements, providing high flexibility. We can write any complex SQL as needed to meet various business needs.

2) Ease of use

MyBatis allows you to easily separate SQL statements from Java code through XML configuration files and annotations, making the code structure clearer and easier to maintain.

3) Simple mapping

MyBatis provides a simple mapping method, which can automatically map the fields in the database table to the properties of the Java object, reducing the complexity of data conversion.

4) Good scalability

MyBatis provides a rich plug-in interface, and you can extend the functions of MyBatis by writing custom plug-ins to meet specific needs. (This part will be explained in the MyBatis course part)

5) Easy to integrate

MyBatis can be seamlessly integrated with popular frameworks such as Spring and Spring Boot to provide a more complete solution.

6) Active community

MyBatis has an active developer community that provides users with rich documentation, tutorials, and support. This helps to quickly find solutions when problems are encountered.

2. SpringBoot's support for MyBatis

Official website address: https://mybatis.org/mybatis-3/

Official reference table: http://mybatis.org/spring/

Chinese official website: https://mybatis.org/mybatis-3/zh/

Mybatis project source address: https://github.com/mybatis/mybatis-3/

We know that it is clearly stated in the official documentation that Spring 2.0 only supports iBatis 2.0. So, we want to add MyBatis3 support to Spring 3.0. Unfortunately, the development of Spring 3.0 ended before the official release of MyBatis 3.0. Since the Spring development team does not want to release an integrated support based on the unreleased version of MyBatis, if you want to get official support from Spring, you can only wait for the next release. Based on the interest in supporting MyBatis in Spring, the MyBatis community believes that it should start convening contributors who are interested in getting involved with integrating Spring as a community sub-project of MyBatis. So, MyBatis made a Spring extension implementation by itself, with a respectable spirit. In addition, this also benefits from Spring's excellent scalability. Based on these two factors, the speed of MyBatis and Spring integration is accelerated.

Correspondence between Spring and MyBatis versions

In actual development, when importing the Mybatis package separately, you can refer to this table.

3. SpringBoot integrates MyBatis in practice

Explanation: This actual combat is still based on the previous SpringBootCase project to integrate MyBatis.

3.1 Case ideas

The query operation on the commodity table in the supply chain is realized through SpringBoot + MyBatis.

3.2 Implementation steps

Step 1: Prepare the database

This is about the windows environment (similar to the linux environment). First start the local mysql database, connect to the local Mysql through the mysql client tool (Navicat, etc.) after startup, and create a new database xintu, specify the database character code as utf-8.

Create a new product table and insert data into the table.

1) Create a new table

DROP TABLE IF EXISTS `t_product`;
CREATE TABLE `t_product` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `category_id` int(10) DEFAULT NULL COMMENT '类目ID',
  `item_type` varchar(50) DEFAULT NULL COMMENT '商品类型',
  `title` varchar(500) DEFAULT NULL COMMENT '商品标题',
  `sell_point` varchar(50) DEFAULT NULL COMMENT '销售站点',
  `price` varchar(50) DEFAULT NULL COMMENT '销售价格',
  `num` int(11) DEFAULT NULL COMMENT '库存数量',
  `image` varchar(500) DEFAULT NULL COMMENT '商品图片',
  `status` int(11) DEFAULT NULL COMMENT '商品状态'
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2) Insert data

INSERT INTO `t_product` VALUES ('1', '23', '12', 'Redmi K50Pro 天玑9000 AMOLED 2K柔性直屏 OIS光学防抖  120W快充 幻镜  8GB+256GB 5G智能手机 小米红米', '仅上海,广州,沈阳仓有货!预购从速', '1469.00', '10', '../images/portal/02COMIXC5902A5122blue/miaosha_1.jpg', '1', '1', null, null, null, null);
INSERT INTO `t_product` VALUES ('2', '23', '12', 'Redmi K50Pro 天玑9000 AMOLED 2K柔性直屏 OIS光学防抖  120W快充 幻镜  8GB+256GB 5G智能手机 小米红米', '仅上海,广州,沈阳仓有货!预购从速', '2619.00', '10', '../images/portal/02COMIXC5902A5122blue/miaosha_2.jpg', '1', '2', null, null, null, null);
I

Step 2: SpringBoot integrates MyBatis plugin

Add related jar dependencies in pom.xml.

<!--引入mybatis jar-->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.4</version>
</dependency>
<!--引入mysql jar-->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.25</version>
</dependency>

Step 3: Configure the data source in application.yml

spring:
  datasource: # mysql相关配置
    url: jdbc:mysql://localhost:3306/xintu?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: xxx

Step 4: Reverse engineer configuration

Introduce the reverse engineering mybatis maven plugin. Since it is necessary to connect to the database when generating Java POJOs, it is also necessary to introduce the mysql driver package.

<!--==========mybatis代码生成插件配置==========-->
<plugin>
	<!--插件坐标-->
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-maven-plugin</artifactId>
	<version>1.3.5</version>
	<!--插件依赖数据库驱动-->
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.25</version>
		</dependency>
	</dependencies>
	<!--插件配置-->
	<configuration>
		<!--指定配置文件位置-->
		<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
		<verbose>true</verbose>
		<overwrite>true</overwrite>
	</configuration>
</plugin>

Introduce the reverse engineering configuration file generatorConfig.xml,

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 :false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--==================数据库连接的信息:驱动类、连接地址、用户名、密码 =====================-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/xintu" userId="root"
                        password="xxx">
        </jdbcConnection>
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- ================targetProject:生成PO类的位置 ================-->
        <javaModelGenerator targetPackage="com.xintu.demo.entity"
                            targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!--================= targetProject:mapper映射文件生成的位置=============== -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject=".\src\main\resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- ==================targetPackage:mapper接口生成的位置 ==================-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.xintu.demo.mapper"
                             targetProject=".\src\main\java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!--=============== 指定数据库表 ==================-->
        <table schema="xintu" tableName="t_product"></table>
    </context>
</generatorConfiguration>

Step 5: Reverse Code Generation

Use Mybatis reverse engineering to generate interfaces, mapping files and entity beans.

 Step 6: Create TProductService and write code

package com.xintu.demo.service;

import com.xintu.demo.entity.TProduct;
import com.xintu.demo.entity.TProductExample;
import com.xintu.demo.mapper.TProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author XinTu
 * @classname TProductService
 * @description TODO
 * @date 2023年04月29日 21:19
 */
@Service
public class TProductService {
    @Autowired
    private TProductMapper mapper;

    /**
     * 查询测试
     * @return
     */
    public List<TProduct> queryList(){
        TProductExample example = new TProductExample();
        TProductExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(1);
        return mapper.selectByExample(example);
    }
}

Step 7: Create TProductController and write code

package com.xintu.demo.controller;

import com.xintu.demo.entity.TProduct;
import com.xintu.demo.mapper.TProductMapper;
import com.xintu.demo.service.TProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author XinTu
 * @classname TProductController
 * @description TODO
 * @date 2023年04月29日 21:12
 */


@RestController
public class TProductController {

    @Autowired
    private TProductService service;

    /**
     * 查询测试
     * @return
     */
    @GetMapping(value = "/queryList")
    public List<TProduct> queryList() {
        return service.queryList();
    }

}

After the TProductMapper generated by MyBatis reverse engineering, there are two injection methods:

① Add a Mapper annotation to the interface

② Add @MapperScan("com.xintu.demo.mapper") annotation to SpringbootApplication startup class

* The role of the above two: MyBatis automatically scans the relationship between the mapping file of the data persistence layer and the DAO interface

package com.xintu.demo.mapper;

import com.xintu.demo.entity.TProduct;
import com.xintu.demo.entity.TProductExample;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper //方式一:添加@Mapper注解,等同于主类上加@MapperScan("com.bjpowernode.springboot.mapper")
public interface TProductMapper {
    long countByExample(TProductExample example);

    int deleteByExample(TProductExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(TProduct record);

    int insertSelective(TProduct record);

    List<TProduct> selectByExample(TProductExample example);

    TProduct selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") TProduct record, @Param("example") TProductExample example);

    int updateByExample(@Param("record") TProduct record, @Param("example") TProductExample example);

    int updateByPrimaryKeySelective(TProduct record);

    int updateByPrimaryKey(TProduct record);
}

Step 8: Specify the mybatis xml path

#在application.yml配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定
mybatis:
  mapper-locations: classpath:mapper/*.xml

Step 9: Test Verification

The above part is an entry-level content, mainly analyzing the characteristics of MyBatis and the actual integration process with SpringBoot. We found that MyBatis conquered SpringBoot (or Spring) mainly by three points:

1) MyBatis has many advantages as the persistence layer itself (low coupling, easy to read and maintain, etc.)

2) The MyBatis community spares no effort to promote

3) SpringBoot's own powerful expansion capabilities

The above three points together create the perfect integration of MyBatis and SpringBoot. More details about MyBatis, such as implementation principles and custom extensions, will be explained one by one in the following MyBatis column.

Guess you like

Origin blog.csdn.net/wangyongfei5000/article/details/130446232