20,000-word summary "MybatisPlus - born to simplify development"

MybatisPlus - Created to Simplify Development


Official website:https://www.sogou.com/link?url=58p16RfDRLuiEHkXxtCPmEiZEcHfFSzq

1. Introduction

MyBatis-Plus (opens new window) MP is a MyBatis (opens new window) Enhancement tools, based on MyBatis, are designed to simplify development and increase efficiency.

2. Characteristics

  • Non-intrusive: Enhance without changing, introduce without affecting existing projects, silky smooth
  • Low loss: automatic injection of basic CURD at startup, basic lossless performance, direct object-oriented operation, BaseMapper
  • Powerful CRUD operations: Built-in generic Mapper, generic Service, most CRUD operations on forms can be accomplished with only a few configurations, and a more powerful conditional constructor to meet all kinds of usage needs (basic CRUDs will not be written by themselves in the future)
  • Supports Lambda-style calls: through Lambda expressions, it is easy to write various query conditions without worrying about field errors
  • Supports auto-generation of primary keys: supports up to four primary key strategies (including distributed unique ID generator-Sequence), can be configured freely, and perfectly solves primary key problems
  • Supports ActiveRecord mode: supports ActiveRecord form calls, and entity classes can perform powerful CRUD operations simply by inheriting Model classes
  • Support for custom global common operations: support for global common method injection (Write once, use anywhere)
  • Built-in code generator: Use code or Maven plug-ins to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations to use (auto code generation)
  • Built-in Paging Plug-in: Based on MyBatis physical paging, developers don't need to worry about specific operations. Once the plug-in is configured, writing paging is equivalent to a normal List query
  • Paging plug-ins support multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and many other databases
  • Built-in performance analysis plug-in: can output SQL statements and their execution time, it is recommended to enable this feature when developing tests to quickly pick up slow queries
  • Built-in global interception plug-in: provides full table delete, update operation smart analysis blocking, or can customize interception rules to prevent misoperation

3. Quick Start

Address:https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B

Using third-party components:

1. Import Corresponding Dependencies

2. Research how to configure dependencies

3. How to Write Code

4. Enhance Expanded Technical Capabilities

step

1. Create database mybatis-plus

2. Create user table

idnameageemail
1Jone18test1@baomidou.com
2Jack20test2@baomidou.com
3Tom28test3@baomidou.com
4Sandy21test4@baomidou.com
5Billie24test5@baomidou.com
DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT 'Primary key ID',
	name VARCHAR(30) NULL DEFAULT NULL COMMENT 'Full name',
	age INT(11) NULL DEFAULT NULL COMMENT 'Age',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT 'mailbox',
	PRIMARY KEY (id)
);

-- Real Development version(Optimistic Lock) deleted(Logical Delete)  gmt_create  gmt_modified

Its corresponding database Data script is as follows:

DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');

3. Write projects, initialize projects, and use SpringBoot to initialize

4. Import Dependency

<!--        Connect to database-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--       lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

<!--        mybatis-plus-->
<!--        mybatis-plus Developed by oneself, not officially-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.3</version>
        </dependency>

Note: Both mybatis and mybatis-plus packages cannot be imported at the same time

5. Connect to the database

#mybatis 5  com.mysql.jdbc.Driver

#mybatis 8 requires time zone, com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Traditional ways: 6, pojo-dao (connect mybatis, configure mapper.xml file) -service-controller

6. Use MybatisPlus

  • pojo
#mybatis 5  com.mysql.jdbc.Driver

#mybatis 8 requires time zone, com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&character=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  • mapper interface
package com.kk.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kk.pojo.User;
import org.springframework.stereotype.Repository;

import java.util.List;

// Implement the basic interface BaseMapper on the corresponding Mapper
@Repository  //Represents a persistent layer
public interface UserMapper  extends BaseMapper<User>{
    List<User> selectList();
    // All CRUD s are written
    //Do not write CRUD s and configuration files as before


}
  • Note: You need to add @MapperScan("com.kk.mapper") to the main program
package com.kk;

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


//Scan our mapper folder
@MapperScan("com.kk.mapper")
@SpringBootApplication
public class MybatisPlusApplication {

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

}
  • test
package com.kk;

import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
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
class MybatisPlusApplicationTests {


    //All methods that inherit BaseMapper BaseMapper can be used
    @Autowired
    private UserMapper userMapper;



    @Test
    void contextLoads() {
        //Parameter is a mapper conditional constructor not used here
        //Query all users
      List<User> users =  userMapper.selectList(null);
      users.forEach(System.out::println);
    }

}

Test it!

4. Configure log output

#Configure Log Output
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

5. Insert Test and Snowflake Algorithm

6. CRUD Extensions

1. Insert operation

//Test Insertion Function
@Test
public void testInsert(){

    User user = new User();
    user.setName("kk");
    user.setAge(17);
    user.setEmail("30666@qq.com");

    //You need a User object here, so you need a new User
    int result = userMapper.insert(user);  //Help us automatically generate IDS
    System.out.println(result);//Number of lines affected
    System.out.println(user);//Found that id is automatically backfilled
}

2. Primary Key Generation Strategy

Default ID_WORKER All Unique IDs

Snowflake algorithm:

Snowflake is an open source distributed ID generation algorithm for Twitter, resulting in a long ID. Its core idea is to use 41 bits as milliseconds, 10 bits as machine ID (5 bits as data center, 5 bits as machine ID), and 12 bits as flow number in milliseconds (meaning 4096 IDs per node per millisecond).Finally, there is a symbol bit, always 0. See the code for the implementation.https://github.com/twitter/snowflake The snowflake algorithm can support TPS of around 4.19 million (2^22*1000).

Primary key self-increasing

Configure Primary Key Self Increase:

1. Write @TableId(type = IdType.AUTO) on the entity class field

2. Database fields must be self-increasing!

Remaining source explanations

public enum IdType {
     
    AUTO(0),//Database ID Self-Increasing  
    NONE(1),//This type is not primary key type set      
    INPUT(2),//User Input ID
      		 //This type can be populated by registering an auto-fill plugin yourself  
    
//The following three types are automatically populated only if the insert object ID is empty.     
    ID_WORKER(3),//Global Unique ID (idWorker)      
    UUID(4),//Global Unique ID (UUID)          
    ID_WORKER_STR(5);//String Globally Unique ID (string representation of idWorker)  
}

Test:

User Entity Class

package com.kk.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    //Corresponding to the primary key in the database (uuid, self-increasing id, snowflake algorithm, redis, zookeeper)
    @TableId(type = IdType.INPUT) //Once you have manually entered the id, you need to configure it yourself
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Test class:

package com.kk;

import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
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
class MybatisPlusApplicationTests {

    //All methods that inherit BaseMapper BaseMapper can be used
    @Autowired
    private UserMapper userMapper;


    //Test Insertion Function
    @Test
    public void testInsert(){

        User user = new User();
        user.setId(6L);
        user.setName("kk");
        user.setAge(17);
        user.setEmail("30666@qq.com");

        //You need a User object here, so you need a new User
        int result = userMapper.insert(user);  //Help us automatically generate IDS
        System.out.println(result);//Number of lines affected
        System.out.println(user);//Found that id is automatically backfilled
    }

}

3. Update Operation

    //Test Update Function
    @Test
    public void testUpdate(){
        User user = new User();
        //Dynamic sql splicing by adjusting auto splicing
        user.setId(6L);
        user.setName("kkkk");
        user.setAge(999);
        //updateById whose parameter is an object
        int i = userMapper.updateById(user);
        System.out.println(i);
    }

4. Automatic Filling

==Creation time, modification time! These operations are automated all the time, do not need to be updated manually!

gmt_create: Creation time, gmt_modified: Modify time opportunity All tables need to be configured and automated

Mode 1: Database level (not recommended for work)

1. Add field create_time,update_time to the table

2. Test the insertion method again

Add Field to Entity Class

private Date createTime;
private Date updateTime;

test

//Test Update Function
@Test
public void testUpdate(){
    User user = new User();
    //Dynamic sql splicing by adjusting auto splicing
    user.setId(6L);
    user.setName("kkkk");
    user.setAge(9999);
    //updateById whose parameter is an object
    int i = userMapper.updateById(user);
    System.out.println(i);
}

Mode 2: Code level

1. Delete the default values of the database, update operation!

2. Additional annotations are needed on field attributes of entity classes

//Remember to use Date under util!!
//Field Add Fill
@TableField(fill = FieldFill.INSERT)
private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

3. Write a processor to handle this annotation

package com.kk.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;


@Slf4j
@Component  //Be careful to add the processor to the IOC container
public class MyMetaObjectHandler implements MetaObjectHandler {
    //Filling strategy at insert time
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ... ...");
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //Filling strategy when updating
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start insert fill ... ...");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

test

    //Test Insertion Function
    @Test
    public void testInsert(){

        User user = new User();
//        user.setId(6L);
        user.setName("qq");
        user.setAge(17);
        user.setEmail("30666@qq.com");

        //You need a User object here, so you need a new User
        int result = userMapper.insert(user);  //Help us automatically generate IDS
        System.out.println(result);//Number of lines affected
        System.out.println(user);//Found that id is automatically backfilled
    }


    //Test Update Function
    @Test
    public void testUpdate(){
        User user = new User();
        //Dynamic sql splicing by adjusting auto splicing
        user.setId(1442085733983649796L);
        user.setName("kkkk");
        user.setAge(99999);
        //updateById whose parameter is an object
        int i = userMapper.updateById(user);
        System.out.println(i);
    }

5. Optimistic Lock

Optimistic lock: As the name implies, always think there will be no problem, no matter what you do not lock! If there is a problem, update the value test again

Pessimistic lock: As the name implies, always think there will be a problem, lock everything! Go ahead and operate!

Optimistic lock implementation:

  • Get the current version when the record is taken out
  • When updating, bring this version with you
  • When performing an update, set version = newVersion where version = oldVersion
  • Update fails if version is incorrect
l Optimistic lock: 1. Query first to get version number version=1
--- A thread
update user set name="kk",version=version+1
where id=2 and version=1

--- B Threads finish first, at this time version=2 Causes A Modification failed
update user set name="kk",version=version+1
where id=2 and version=1

Optimistic Lock Plugin for Testing MP

1. Add version fields to the database

2. Entity class adds corresponding fields

@Version  //Comments on the lock of optimism
private Integer version;

3. Register Components

package com.kk.config;


import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//Scan our mapper folder
@MapperScan("com.kk.mapper")
@EnableTransactionManagement
@Configuration  //Configuration class needs to be added
public class MybatisConfig {

    //Register Optimistic Lock Plugin

        /**
         * Old Version
         */

       /* @Bean
        public OptimisticLockerInterceptor optimisticLockerInterceptor() {
            return new OptimisticLockerInterceptor();
        }*/

        /**
         * new edition
         */
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() {
            MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
            mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
            return mybatisPlusInterceptor;
        }
}

4. Testing

//    Test Optimistic Lock - Success
    @Test
    public void testmybatisPlusInterceptor(){
        //1. Query user information
        User user = userMapper.selectById(1L);
        //2. Modify user information
        user.setName("kk");
        user.setEmail("0000@qq.com");
        //3. Perform update operations
        userMapper.updateById(user);
    }


//    Test Optimistic Lock - under Failed Multithreads

@Test
public void testmybatisPlusInterceptor2(){

        //Thread 1
    User user = userMapper.selectById(1L);
    user.setName("kk111");
    user.setEmail("0000@qq.com");

    //Simulate another thread to perform queue insertion
    User user2 = userMapper.selectById(1L);
    user2.setName("kk222");
    user2.setEmail("0000@qq.com");
    userMapper.updateById(user2);


    //You can use a spin lock to attempt multiple submissions
    userMapper.updateById(user);  //Override the value of the queue-inserting thread if there is no optimistic lock
}

7. Query Operations

//Test Query (Test Bulk Query)
    @Test
    public void  testSelectById(){
//        User user = userMapper.selectById(1L);
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1,2,3));
        users.forEach(System.out::println);
    }

    //Conditional Query map Operation

    @Test
    public void testSelectByBatchIds(){
        HashMap<String, Object> map = new HashMap<>();
        //Customize the conditions to be queried
        map.put("name","kk");
        map.put("age","17");

        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

8. Paging Query

MbatisPlus built-in paging plugin

1. Configure Interceptor Components

    // Old Version
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // Set the requested page to be larger than the maximum page, true calls back to the home page, false continues to request the default false
        // paginationInterceptor.setOverflow(false);
        // Set maximum single page limit, default 500, -1 unrestricted
        // paginationInterceptor.setLimit(500);
        // Turn on join optimization for count, only partially left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
    
    // The latest version
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

2. Use Page object directly

//Test Paging Query
@Test
public void testPage(){
    //Parameter 1 Current Page
    //Parameter 2 Page Size
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
}

9. Delete Operation

       //Test Delete
    @Test
    public void testDeleteById(){
        userMapper.deleteById(1442085733983649796L);
    }

    //Bulk by Delete
    @Test
    public  void testDeleteBatchId(){
        userMapper.deleteBatchIds(Arrays.asList(1442085733983649794L,1442085733983649795L));
    }

    //Delete by map
    @Test
    public void testDeleteMap(){
       HashMap<String,Object> map = new HashMap<>();
       map.put("name","Tom");
        userMapper.deleteByMap(map);
    }

9. Logical Delete

Physical Delete: Remove directly from the database

Logical Delete: Not removed from the database, but invalidated by a variable!Deleted=0=>deleted=1

Administrators can view deleted records!Prevent data loss, like a recycle bin!

Test:

1. Add a deleted field to the data table

2. Adding attributes to entity classes

//Logical Delete
@TableLogic
private Integer deleted;

3. Configuration (the new version of Mybatis does not use this method below)

config

//Registration Logic Delete
@Bean
public ISqlInjector sqlInjector(){
    return new LogicSqlInjector();
}

application.properties

# Configuration Logical Delete Component
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

Actually executing real-time update

10. Performance Analysis Plug-in

Role: Performance analysis interceptor for entering daily SQL statements and their execution time

MybatisPlus provides a performance analysis plug-in and stops running if it exceeds this time!

1. Import Plugins

   /**
     * SQL Execution efficiency plug-in
     */
    @Bean
    @Profile({"dev","test"})// Set the dev test environment on to ensure our efficiency
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100); //ms sets the maximum time sql will execute if it exceeds
        performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

2. Configuration

#  Set up development environment
spring.profiles.active=dev

3. Testing

//Test Paging Query
@Test
public void testPage(){
    //Parameter 1 Current Page
    //Parameter 2 Page Size
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
}

11. Conditional Query Wrapper

Some complex sql can be replaced by wrapper

1. Test 1:

package com.kk;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kk.mapper.UserMapper;
import com.kk.pojo.User;
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
public class WrapperTest {

    //All methods that inherit BaseMapper BaseMapper can be used
    @Autowired
    private UserMapper userMapper;


    @Test
    void contextLoads() {
      //Users older than or equal to 18 years who query for a user whose name is not empty and whose mailbox is not empty
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age",18);
        userMapper.selectList(wrapper).forEach(System.out::println);
    }
}

2. Test 2

@Test
 void test2(){
    //Query name equals zz
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","Small White");
    User user = userMapper.selectOne(wrapper);  //Query a data
    // If there are multiple data results, use list or Map
    System.out.println(user);
}

Note: deleted=1 is undetectable

3. Test 3

@Test
void test3(){
    //Query users aged 18-35
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.between("age",20,35);

    Long count = userMapper.selectCount(wrapper);//Number of query results
    System.out.println(count);
}

‚Äč

4. Test 4

//Fuzzy Query
@Test
void test4(){
    //Query users aged 18-35
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //Left and right e% (on right)%e (on left)
    wrapper
            .notLike("name","e")
            .likeRight("email","t");

    List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
    maps.forEach(System.out::println);
}

5. Test 5

@Test
void test5(){

    QueryWrapper<User> wrapper = new QueryWrapper<>();
   //id found in subquery
    wrapper.inSql("id","select id from user where id <3");


    List<Object> objects = userMapper.selectObjs(wrapper);
    objects.forEach(System.out::println);
}

6. Test 6

    //Query Sorting
@Test
void test6(){

    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //Sort by id
    wrapper.orderByDesc("id");
    //Desc Descending
    //Asc Ascending


    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

12. Code Generator

AutoGenerator is the code generator for MyBatis-Plus. AutoGenerator can quickly generate code for Entity, Mapper, Mapper XML, Service, Controller and other modules, which greatly improves the development efficiency.

Import all dependencies

<dependencies>


    <!-- template engine velocity-engine-core-->
<!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity-engine-core -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>
    
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>






    <!-- Database Driver -->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>

    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
    </dependency>
    <!-- mybatis-plus -->
    <!-- mybatis-plus It's self-developed, not official! -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.0.5</version>
    </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>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

Note: If the engine package and the dependent package for this lang3 cannot be imported, you need to create a lib folder in the project, import the two packages, and add them as libraries

Test:

package com.kk;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;


import java.util.ArrayList;

//Code Auto Generator
public class KkCode {
    public static void main(String[] args) {
        // A code Auto-Generator object needs to be built
        AutoGenerator mpg = new AutoGenerator();

        // Configuration Policy
        // 1. Global Configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath+"/src/main/java");
        gc.setAuthor("kk"); gc.setOpen(false);
        gc.setFileOverride(false);

        // Whether to Overwrite
        gc.setServiceName("%sService");

        // I prefix to de-Service
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        //2. Setting up data sources
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc);

        //3. Configuration of packages
        PackageConfig pc = new PackageConfig();
        //Simply change the entity class name, package name, and database configuration
        pc.setModuleName("blog");
        pc.setParent("com.kk");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        //4. Policy Configuration
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");

        // Set the table name to map
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);

        // Automatic lombok;
        strategy.setLogicDeleteFieldName("deleted");

        // Automatic Fill Configuration
        TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();

        tableFills.add(gmtCreate); tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);

        // Optimistic Lock
        strategy.setVersionFieldName("version");
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);

        // localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.execute(); //implement
    }

}

The test was successful!

troller");
mpg.setPackageInfo(pc);

    //4. Policy Configuration
    StrategyConfig strategy = new StrategyConfig();
    strategy.setInclude("user");

    // Set the table name to map
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    strategy.setEntityLombokModel(true);

    // Automatic lombok;
    strategy.setLogicDeleteFieldName("deleted");

    // Automatic Fill Configuration
    TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
    TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
    ArrayList<TableFill> tableFills = new ArrayList<>();

    tableFills.add(gmtCreate); tableFills.add(gmtModified);
    strategy.setTableFillList(tableFills);

    // Optimistic Lock
    strategy.setVersionFieldName("version");
    strategy.setRestControllerStyle(true);
    strategy.setControllerMappingHyphenStyle(true);

    // localhost:8080/hello_id_2
    mpg.setStrategy(strategy);
    mpg.execute(); //implement
}

}

==The test was successful!==

![img](https://img-blog.csdnimg.cn/img_convert/1ff6bf8070dab21b36430158813af540.png)

Tags: Java Database MybatisPlus

Posted on Sun, 03 Oct 2021 12:21:09 -0400 by thebighere