【Spring Boot】3.3 MyBatisPlus FastAutoGeneration

荀嘉熙
2023-12-01

MyBatisPlus 自带的代码生成器

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

import java.util.Collections;

/***
 * Author: YL.Lou
 * Class: FastAutoGeneratorTool
 * Project: washes_base_backstage
 * Introduce: 文件自动生成器
 * DateTime: 2022-06-27 16:29
 ***/

public class FastAutoGeneratorTool {
    public static void main(String[] args){
        FastAutoGenerator.create("jdbc:mariadb://xxx.com:3306/washes?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&allowPublicKeyRetrieval=true", "xxx", "123")
                .globalConfig(builder -> {
                    builder.author("LouYunlong") // 设置作者
                            //.enableSwagger() // 开启 swagger 模式
                            //.fileOverride() // 覆盖已生成文件
                            .outputDir("D:\\Developments\\WebProjects\\SpringBoots\\xxx_backstage\\base\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("cn.ihuanxi.base") // 设置父包名
                            //.moduleName("") // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\Developments\\WebProjects\\SpringBoots\\xxx_backstage\\base\\src\\main\\resources\\mappers")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("w_user") // 设置需要生成的表名
                            .addTablePrefix("w_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();

    }
}

基础的使用非常简单,把上边的文件在Test中创建后根据注释修改必要的参数,运行就可以得到Entity/Mapper/Service/Controller的相关代码,还能得到一个XML的Mapper。这就是代码自动生成器的作用。

调整

但是使用默认模板生成的代码是需要调整的:

  • 在 Application.class 上增加 @MapperScan(“cn.ihuanxi.base.mapper”) 注解 用来指名Mapper位置
  • 修改自动创建的Controller文件中的 Controller注解 为 RestController
  • 检查Controller层中 RequestMapping()中的包名是否正确 配置文件如果增加了父包名会在此处体现
  • 生成器中的包名设置 不需要考虑 appliction.properties中的 context-path
  • 在 Controller 中增加基础代码 复制粘贴即可

注意

  • 在ServiceImpl中注入Result和Mapper,此处Mapper会飘红 只需要在Mapper接口上增加注解 @Repository即可
  • 需要修改entity类 如果不是Auto_Increment 时,Generator不会生成主键注解
  • 在实体类添加 @TableId(value = "u_id")因为使用雪花算法,所以不需要定义type类型
  • 另外需要在实体类中 为 password 属性增加 @JsonIgnore注解 如此,该实例就不会返回到JSON中
  • 为日期时间相关的字段增加 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", locale = "GMT+8") 来格式化时间
  • 对于数据库中没有对应字段的实体类属性 @TableField(exist = false)可以用来标记

踩坑

Lombok 和 Jackson 在处理 Entity 的时候 会有一些冲突,这个后续有时间专门写一下。

 类似资料: