SpringBoot integrates MyBatis-Plus introductory experience

Keywords: Programming Mybatis MySQL xml Database

I. Preface

This article will integrate MyBatis-Plus based on SpringBoot. MyBatis-Plus is an enhancement tool for MyBatis, which enhances MyBatis without changing its original function.~

2. SpringBoot Integration MyBatis-Plus

Basic environment
  1. spring-boot 2.1.8
  2. mybatis-plus 2.2.0
  3. mysql 5.7.24
  4. maven project

1. Introducing MyBatis-Plus dependencies into pom.xml

Next, paste the whole document content of the small edition directly for reference, so as to avoid errors caused by missing some details.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhengqing</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mybatis-plus-boot-starter.version>2.2.0</mybatis-plus-boot-starter.version>
        <mysql.version>5.1.40</mysql.version>
        <commons-lang3.version>3.6</commons-lang3.version>
        <hutool-all.version>4.6.2</hutool-all.version>
    </properties>

    <dependencies>
        <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>

        <!-- mybatis-plus begin =================================== -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatis-plus-boot-starter.version}</version>
        </dependency>
        <!-- mybatis-plus end -->

        <!-- ========================= Database correlation ========================== -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!-- Ali database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.18</version>
        </dependency>

        <!-- ========================= Common library dependencies ========================== -->
        <!-- lombok Plug-in unit -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Hutool Tool class -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool-all.version}</version>
        </dependency>
        <!-- StringUtils Tool class -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>
    </dependencies>

    <build>
        <!-- Note: maven The default is not compiled, so add the following resources Only then will the corresponding production be produced. xml Document Purpose: Resolution mybatis Mapping relationship miscorrespondence  start =============== -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </testResource>
        </testResources>
        <!-- Note: maven The default is not compiled, so add the following resources Only then will the corresponding production be produced. xml Document Purpose: Resolution mybatis Mapping relationship miscorrespondence  end =============== -->

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2. MyBatis-Plus configuration class

Here we mainly configure paging plug-ins and @MapperScan annotations to scan Mapper folders

@EnableTransactionManagement
@Configuration
@MapperScan("com.zhengqing.demo.modules.**.mapper*") // Scanning the Mapper folder
public class MybatisPlusConfig {
    /**
     * mybatis-plus Paging plug-in <br>
     * Document: https://mp.baomidou.com/guide/page.html <br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

3. Configuration of database and mybatis-plus configuration in application.yml

Warm Tip: Pay attention to modifying your database connection configuration information~

# configure port
server:
  port: 8080
  servlet:
    #    context-path: /api
    application-display-name: demo

spring:
    application:
        name: demo
    profiles:
      active: dev
    # Configuring data sources
    datasource:
      url: jdbc:mysql://127.0.0.1:3306/demo? Allow MultiQueries = true & useUnicode = true & characterEncoding = UTF8 & zeroDateTime Behavior = convertToNull & useSSL = false # MySQL in high versions need to specify whether or not to make an SSL connection solution plus & useSSL = false
      name: demo
      username: root
      password: root
      # Using druid data source
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      filters: stat
      maxActive: 20
      initialSize: 1
      maxWait: 60000
      minIdle: 1
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: select 'x'
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20

management:
  security:
    enabled: false

# Configuration of mybatis plus
mybatis-plus:
  # XML scanning, where multiple directories are separated by commas or semicolons (telling Mapper the location of the corresponding XML file)
  mapper-locations: classpath:**/*Mapper.xml
  # The following configurations have default values and can be set without setting
  global-config:
    #Primary key type 0: "database ID self-increasing", "user input ID", "global unique ID", "global unique ID", "global unique ID", "global unique ID UUID";
    id-type: 0
    #Field Strategy 0: "Ignore Judgment", "Non-NULL Judgment", "Non-empty Judgment"
    field-strategy: 2
    #Conversion of Hump Underline
    db-column-underline: true
    #Refresh mapper debugging artifact
    refresh-mapper: false
    #Database Uppercase Underline Conversion
    #capital-mode: true
    #Sequence Interface Implementing Class Configuration
    #key-generator: com.baomidou.springboot.xxx
    #Logical Delete Configuration
    #logic-delete-value: 0 # Logically deleted values (default 1)
    #logic-not-delete-value: 1 # Logical Undeleted Value (default 0)
    #Implementation of Custom Filling Policy Interface
#    meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
    #Custom SQL Injector
    #sql-injector: com.baomidou.springboot.xxx
  configuration:
    # Whether to turn on Automatic Hump naming rule mapping: a similar mapping from database column names to Java attribute hump naming
    map-underscore-to-camel-case: true
    cache-enabled: false
    # If the query results contain columns with null values, MyBatis does not map this field when mapping
#    call-setters-on-nulls: true
    # This configuration prints out the sql executed and can be used during development or testing
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # Resolve the problem that oracle cannot convert errors when updating data to null, and mysql will not.
    jdbc-type-for-null: 'null'

III. simulation business code - CRUD user information table

1. New t_sys_user user table in database

2. Writing Entity Classes

Warm Tip: Entity class inherits MyBatis-Plus Model class + Mapper class inherits MyBatis-Plus BaseMapper class - > can support ActiveRecord dynamic grammar calls

@Data
@TableName("t_sys_user")
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    /**
     * Primary key ID
     */
	@TableId(value="id", type= IdType.AUTO)
	private Integer id;
    /**
     * Account number
     */
	@TableField("username")
	private String username;
    /**
     * Login password
     */
	@TableField("password")
	private String password;
    /**
     * Nickname?
     */
	@TableField("nick_name")
	private String nickName;

	@Override
	protected Serializable pkVal() {
		return this.id;
	}
}

3. Writing Mapper classes

public interface UserMapper extends BaseMapper<User> { }

IV. Testing CRUD

Warm Tip: The following CRUD s all use ActiveRecord dynamic grammar

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    /**
     * New data
     */
    @Test
    public void testAdd() throws Exception{
        User entity = new User();
        entity.setUsername("admin");
        entity.setPassword("123456");
        entity.setNickName("Administrators");
        entity.insert();
    }

    /**
     * Update data
     */
    @Test
    public void testUpdate() throws Exception{
        User entity = new User();
        entity.setId(1);
        entity.setUsername("test");
        entity.setPassword("123456");
        entity.setNickName("Test number");
        entity.updateById();
    }

    /**
     * Delete data
     */
    @Test
    public void testDelete() throws Exception{
        User entity = new User();
        entity.deleteById(1);
    }


    /**
     * Query specified id data
     */
    @Test
    public void testSelectById() throws Exception{
        User entity = new User();
        User user = entity.selectById(1);
        System.out.println(user);
    }

    /**
     * Query all data
     */
    @Test
    public void testSelectAll() throws Exception{
        User entity = new User();
        List list = entity.selectList(null);
        System.out.println(list);
    }

    /**
     * Query all data - paging
     */
    @Test
    public void testSelectAllPage() throws Exception{
        User entity = new User();
        Page<User> page = entity.selectPage(new Page<User>(1, 10), null);
        System.out.println(page);
    }
}

V. Native MyBatis Approach

Let's put the demo source code at the end of this case, not to mention more, that is to say, write sql statements to deal with the corresponding business.

Six, summary

  1. Introducing Relevant Dependencies
  2. MyBatis-Plus Core Configuration - Packet Sweeping, Aliases, Paging Plug-ins, etc.
  3. Write business code tests

Overall, it's relatively simple. For more grammar and functions about MyBatis-Plus, refer to the MyBatis-Plus official documentation.

https://mp.baomidou.com/guide/crud-interface.html#mapper-crud-%E6%8E%A5%E5%8F%A3

Overall project structure:

The source code of this case

https://gitee.com/zhengqingya/java-workspace

The actual operation of the project can be referred to:
GitHub address: https://github.com/zhengqingya/code-generator
Code Cloud Address: https://gitee.com/zhengqingya/code-generator

This article by the blog article multiple platform OpenWrite Release!

Posted by Oren on Thu, 10 Oct 2019 19:58:11 -0700