MybatisPlus代码生成器

MybatisPlus存在代码生成器,能够根据数据库做到代码的一键生成。

首先我们创建一新的项目,接着导入依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3.1</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.3.1</version>
</dependency>
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

然后配置一下数据源:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

接着就可以编写自动生成脚本,这里选择测试类,用到FastAutoGenerator作为生成器:

@Configurable
class DemoApplicationTests {
    @Resource
    DataSource dataSource;
    @Test
    void contextLoads() {
        FastAutoGenerator
                .create(new DataSourceConfig.Builder(dataSource))
                // 配置一下全局设置
                .globalConfig(builder -> {
                    builder.author("lbw");              //作者信息,一会会变成注释
                    builder.commentDate("2024-01-01");  //日期信息,一会会变成注释
                    builder.outputDir("src/main/java"); //输出目录设置为当前项目的目录

                })
                // 配置打包设置,也就是项目生成的包
                .packageConfig(builder -> builder.parent("com.example"))
                .strategyConfig(builder -> {
                    builder
                            .mapperBuilder()
                            .mapperAnnotation(Mapper.class)
                            .build();
                })
                .execute();

    }
}

之后我们就可以运行这个脚本,代码生成器会自动生成从Mapper到Controller的所有代码,我们就只需要去完成业务逻辑就可以了。

对于一些有特殊要求的用户来说,我们希望能够以自己的模版来进行生产,怎么才能修改它自动生成的代码模版呢,我们可以直接找到mybatis-plus-generator的源码:

生成模版都在在这个里面有写,我们要做的就是去修改这些模版,变成我们自己希望的样子,由于默认的模版解析引擎为Velocity,我们需要复制以.vm结尾的文件到resource随便一个目录中,然后随便改:

接着我们配置一下模版:

@Test
void contextLoads() {
    FastAutoGenerator
            ...
      			.strategyConfig(builder -> {
                builder
                        .mapperBuilder()
                        .enableFileOverride()   //开启文件重写,自动覆盖新的
                        .mapperAnnotation(Mapper.class)
                        .build();
            })
            .templateConfig(builder -> {
                    builder.controller("/template/controller.java.vm");
            })
            .execute();
}

这样,新生成的代码中就是按照我们自己的模版来定义了,需要修改其他类模版只需要调用不同的builder的方法就行了。