1

1 Introduction

The use of MyBatis Plus was introduced in the previous article, here is an article to combine with Spring Boot to introduce the use of the code generator.

2 Why code generators are needed

Use the code generator to generate some fixed template code, such as:

  • Controller layer code
  • Service layer code
  • mapper
  • entity class

For example, a User class can generate the following code:

在这里插入图片描述

3 Environment

The environment used in this example is as follows:

  • MyBaits Plus 3.5.1
  • MyBatis Plus Generator 3.5.2

4 Prepare the data sheet

 DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;
CREATE TABLE user(
    id BIGINT PRIMARY KEY ,
    name VARCHAR(30) NOT NULL
);

5 Create a project and import dependencies

Create a new Spring Boot project and import the following dependencies:

 runtimeOnly 'mysql:mysql-connector-java'
implementation 'com.baomidou:mybatis-plus-boot-starter:3.5.1'
implementation 'com.baomidou:mybatis-plus-generator:3.5.2'
implementation 'org.freemarker:freemarker:2.3.31'

除了starter generator外,还需要一个模板引擎(可选VelocityFreemarkerBeetl , Default Velocity ), here is Freemarker .

Maven version is as follows:

 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.29</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version>
</dependency>

6 Create a new generator class

This class is used for configuration for code generation:

 import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

public class Generator {
    public static void main(String[] args) {
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/test", "root", "123456")
        .globalConfig(builder ->
                builder.author("author").outputDir(System.getProperty("user.dir") + "/src/main/java")
                .build())
        .packageConfig(
                builder -> builder.parent("com.example.demo").moduleName("user").build())
        .strategyConfig(
                builder -> builder.addInclude("user").entityBuilder().enableLombok()
                        .disableSerialVersionUID().build()
        )
        .templateEngine(new FreemarkerTemplateEngine())
        .execute();
    }
}

Briefly talk about the configuration:

  • create() : Parameters for database connection
  • globalConfig() : Author, output directory
  • packageConfig() : parent package name, module name
  • strategyConfig() : tables included, enabled Lombok models, disabled generation serialVersionUID
  • templateEngine() : Set the template engine, pay attention to import the corresponding dependencies, here is Freemarker

When ready, run main directly, and a user folder will be generated under src/main/java 1d5dd21809548e9b3203c1fe60fcc8e0---:

在这里插入图片描述

7 Test run

First modify the configuration file and add a data source:

 spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456

Modify UserController as follows, add a test method:

 @RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {
    private final UserServiceImpl userService;

    @GetMapping("/test")
    public String test() {
        return userService.getById(1).toString();
    }
}

At this point, if you try to run main method directly, the following error will be reported:

在这里插入图片描述

Can't find UserMapper this Bean , the solution is to add a @Mapper in UserMapper ---

 @Mapper
public interface UserMapper extends BaseMapper<User> {
}

Or add a @MapperScan to the main class and add the fully qualified path where mapper is located:

 @SpringBootApplication
@MapperScan("com.example.demo.user.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

In this way, if you access localhost:8080/test , you can access the user of id=1 :

在这里插入图片描述

8 Other configurations

The above only introduces the simplest generator configuration. In fact, the complete code generator configuration is as follows:

  • DataSourceConfig : data source configuration, including database type, driver, connection URL , username, password, etc.
  • GlobalConfig : Global configuration, you can specify the author, output code directory, etc., and support Kotlin and Swagger2
  • PackageConfig :包配置,指定代码生成的包名,包括mapper包名、 service包名、 controller包名等
  • TemplateConfig :模板配置,可以自定义生成的模板,包括entity模板、 service模板、 controller模板、 mapper template, mapper xml template, etc.
  • InjectionConfig : injection configuration, you can customize the configuration Map object, etc.
  • StrategyConfig :策略配置,包含Entity a243450196c978b3befeaa4893ae1667---策略配置、 ControllerService Mapper策略Configuration, you can set the parent class, set the name of some files, etc.

Please check the official documentation for details.

9 Reference source code

Java Version:

Kotlin Version:

10 Reference Links


氷泠
420 声望647 粉丝