springboot integrates mybatis (with complete demo)

springboot-mybatis learning record📝

table of Contents

Overall code structure

Project address: https://github.com/rowlingz/springboot_mybatis_learn

Insert picture description here

Introduce dependencies and configuration

-pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springboot_mybatis_learn</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.4.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>

        <!--        mybatis-generator 自动生成依赖-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.6</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!-- mybatis.generator  -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>

                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.21</version>
                        <scope>runtime</scope>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

It should be noted here that there will be unsuccessful operation due to version problems between dependencies. There are two methods here:
1. Use spring-boot-starter-parent to manage the relevant versions uniformly.
2. Or go to maven to check the dependencies used by Managed Dependencies when importing the package to ensure that the versions of each reference are consistent.

-application.xml

Configuration file

spring:
  application:
    name: mybatis-demo
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?charset=utf8&autocommit=true&autoReconnect=true&serverTimezone=GMT%2B8
    username: root
    password: root
    driverClassName: com.mysql.cj.jdbc.Driver
mybatis:
  # 配置 mybatis 的configuration 文件位置
#  config-location: classpath:mybatis/mybatis-config.xml
  # 配置 mapper 文件的位置
  mapper-locations: classpath:mapper/*.xml
  # 配置别名, 默认是类名首字母小写;也可以使用@Alias
  type-aliases-package: com.rowlingz.mybatis.entity
  # configuration 配置 config-location 和 configuration 不能同时配置
  configuration:
    # 下划线转大写映射实体类字段
    map-underscore-to-camel-case: true

There are two points to note here:
1. You can add serverTimezone=GMT%2B8 to specify the date and time zone in the database address url, and modify the time zone according to your needs.
2. DriverClassName, if the mysql version is MySQL5, use com.mysql.jdbc.Driver; For higher versions, use com.mysql.cj.jdbc.Driver

-generatorConfig.xml

Used to automatically generate mybatis-related entity classes, ***map.xml, and mapxml corresponding client. You can modify it according to your needs, so I won’t talk about it here.

<?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>
    <!--    &lt;!&ndash; 引入配置文件 &ndash;&gt;-->
    <properties resource="application.yml"/>
    <!-- 指定数据连接驱动jar地址 -->
    <classPathEntry location="/Users/zhouning/.m2/repository/mysql/mysql-connector-java/8.0.15/mysql-connector-java-8.0.15.jar" />

    <!-- 一个数据库一个context -->
    <context id="ingtube_data">
        <!-- 注释 -->
        <commentGenerator >
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/test?charset=utf8&quot;autocommit=true&quot;autoReconnect=true"
                        userId="root"
                        password="root" />

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.rowlingz.mybatis.entity"
                            targetProject="src/main/java" >
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="src/main/resources" >
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>

        <!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator targetPackage="com.rowlingz.mybatis.mapper"
                             targetProject="src/main/java" type="MAPPER" >
            <!-- 是否在当前路径下新加一层schema,eg:fase路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

        <!--         配置表信息-->
        <table tableName="production_tag_feedback_calcu" domainObjectName=""
               enableCountByExample="false" enableSelectByPrimaryKey="false" enableDeleteByPrimaryKey="false"
               enableUpdateByPrimaryKey="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false"
        >
            <!-- 忽略列,不生成bean 字段 -->
            <ignoreColumn column="id" />
            <ignoreColumn column="create_time" />
            <ignoreColumn column="update_time" />
        </table>

    </context>
</generatorConfiguration>

Then you can manually generate the relevant files in the IDE plug-in execution. Of course, you can also create these files manually.

Insert picture description here


After the execution is completed, the following files are generated respectively

src/main/resources/mapper/ProductionTagFeedbackCalcuMapper.xml
src/main/java/com/rowlingz/mybatis/mapper/ProductionTagFeedbackCalcuMapper.java
src/main/java/com/rowlingz/mybatis/entity/ProductionTagFeedbackCalcu.java

Manually add sql example

ProductionTagFeedbackCalcuMapper.java file

package com.rowlingz.mybatis.mapper;

import com.rowlingz.mybatis.entity.ProductionTagFeedbackCalcu;

import java.util.List;


public interface ProductionTagFeedbackCalcuMapper {
    List<ProductionTagFeedbackCalcu> list();
}


The id here in ProductionTagFeedbackCalcuMapper.xml should be matched with the mapper method, and then the resultType should refer to the corresponding entity class

<?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" >
<mapper namespace="com.rowlingz.mybatis.mapper.ProductionTagFeedbackCalcuMapper" >
  <select id="list" resultType="com.rowlingz.mybatis.entity.ProductionTagFeedbackCalcu">
    select production_id, category_path, in_stock_time,
    status, is_tbk, tag_id,
    feedback_count, feedback_sum, feedback_avg from production_tag_feedback_calcu limit 3
  </select>
</mapper>

Application.java

In Application.java,
remember to use @MapperScan to specify the package where the interface that is to become the implementation class is located. All interfaces under the package will generate the corresponding implementation class after compilation.

package com.rowlingz.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com/rowlingz/mybatis/mapper")
public class Application {

    public static void main(String[] args) {
        new SpringApplication(Application.class).run(args);
    }
}

test

Write the test file UserMapperTest.java

package com.rowlingz.mapper;

import com.rowlingz.mybatis.Application;
import com.rowlingz.mybatis.entity.ProductionTagFeedbackCalcu;
import com.rowlingz.mybatis.mapper.ProductionTagFeedbackCalcuMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest(classes = Application.class)
public class UserMapperTest {

    @Autowired
    ProductionTagFeedbackCalcuMapper mapper;

    @Test
    public void list() {
        List<ProductionTagFeedbackCalcu> result = mapper.list();
        for (ProductionTagFeedbackCalcu value : result) {
            System.out.println(value);
        }
    }

}

Screenshot of test results:

Insert picture description here