Introduction and use of MyBatis-Plus

1. Introduction to MyBatis-Plus

MyBatis-Plus is a MyBatis enhancement tool. The enhancement is made on the basis of MyBatis without any changes. It is born to simplify development and improve efficiency.

The following picture from the official website of MyBatis-Plus vividly reflects the relationship between MyBatis and MyBatis-Plus:

Insert picture description here

Second, characteristics

  • No intrusion : only enhance and do not change, the introduction of it will not affect the existing project, it is as smooth as silk
  • Low loss : basic CURD will be automatically injected at startup, performance is basically no loss, direct object-oriented operation
  • Powerful CRUD operations : built-in general Mapper, general service, only a small amount of configuration can realize most of the CRUD operations of a single table, and a more powerful condition builder to meet various usage requirements
  • Support Lambda form call : through Lambda expressions, you can easily write all kinds of query conditions, no need to worry about writing wrong fields
  • Supports automatic primary key generation : supports up to 4 primary key strategies (including a distributed unique ID generator-Sequence), which can be configured freely, which perfectly solves the primary key problem
  • Support ActiveRecord mode : Support ActiveRecord form call, entity classes only need to inherit Model class to perform powerful CRUD operations
  • Support custom global general operations : support global general method injection (Write once, use anywhere)
  • Built-in code generator : Use code or Maven plug-in to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations for you to use
  • Built-in paging plug-in : Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
  • Paging plugin supports multiple databases : supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
  • Built-in performance analysis plug-in : Sql statement and its execution time can be output. It is recommended to enable this function during development and testing to quickly detect slow queries
  • Built-in global interception plug-in : Provides intelligent analysis and blocking of delete and update operations of the entire table, and can also customize interception rules to prevent misoperations

Third, the frame structure

Insert picture description here

Fourth, start using MyBatis-Plus

Before officially speaking about MyBatis-Plus, it is assumed that you have:

Have a Java development environment and corresponding IDE

Proficiency in Java language programming

Familiar with Spring Boot

Familiar with Maven

(I have written more or less of these before, if you are interested, you can click on my homepage to see)

Insert picture description here

First use the following SQL script to build a table and insert data:

#创建user表
CREATE TABLE user(
	id BIGINT(20) NOT NULL COMMENT '主键ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
	age INT(11) NULL DEFAULT NULL COMMENT '年龄',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
	PRIMARY KEY (id)
);

#插入几条记录
INSERT INTO user (id, name, age, email) VALUES
(1, '寒山月初℃', 21, 'test_emil1'),
(2, '李平安', 20, 'test_emil2'),
(3, '李健康', 22, 'test_emil3'),
(4, '李富贵', 21, 'test_emil4'),
(5, '李牛逼', 24, 'test_emil5');

Initialize the Spring Boot project:

Create an empty Spring Boot project.

(I wrote the blog about creating Spring Boot project, if you need it, you can refer to my homepage)

Add dependency:

Introduce the Spring Boot Starter parent project:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0</version>
    <relativePath/>
</parent>

Introduction of spring-boot-starter, spring-boot-starter-test, mybatis-plus-boot-starter, mysqldependent on:

<dependencies>
    
    <!--`spring-boot-starter`-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
    <!--`spring-boot-starter-test`-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <!-- mybatis-plus-boot-starter-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>
    
    <!-- mysql -->
    <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

Configuration

Add database related configuration in the application.yml configuration file

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_db?characterEncoding=utf-8&useS SL=false&serverTimezone=Asia/Shanghai
    username: root
    password:
    driver-class-name: com.mysql.cj.jdbc.Driver

Add Spring Boot startup class @MapperScannotes, scanning Mapper folder:

package com.ljt.springbootdemo;

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

@SpringBootApplication
@MapperScan(basePackages = "com.ljt.springbootdemo.dao")
public class SpringbootApplication {

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

coding

Write entity class User.java

class User {
    private Long id;
    private String name;
    private Integer age;

    public Long getId() {
         return id;
    }

    public void setId(Long id) {
         this.id = id;
    }

    public String getName() {
         return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    public Integer getAge() {
         return age;
    }

    public void setAge(Integer age) {
         this.age = age;
    }

    public String getEmail() {
         return email;
    }

    public void setEmail(String email) {
         this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", account='" + account + '\'' +
                ", age=" + age +
                '}';
    }
}

Write the Mapper interface UserMapper.java to implement the BaseMapper interface

public interface UserMapper extends BaseMapper<User> {

}

test

Write test classes and perform functional tests:

@SpringBootTest
public class Test {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        List<User> userList = userMapper.selectList();
		for(User u : userList) {
            System.out.println(u);
        }
    }

}

Console output:

User{id=1, name=寒山月初℃, age=21, email=test_emil1}
User{id=2, name=李平安, age=20, email=test_emil2}
User{id=3, name=李健康, age=22, email=test_emil3}
User{id=4, name=李富贵, age=21, email=test_emil4}
User{id=5, name=李牛逼, age=24, email=test_emil5}