AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
1 添加依赖
模版引擎默认使用velocity,如果使用其他模版引擎需要在generator.setTemplateEngine()中进行设置。
<!-- 代码自动生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 添加模板引擎依赖 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
2 准备工作
2.1 准备一张日志表
2.2 在application.yml中添加配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 配置日志
global-config: # 配置逻辑删除
db-config:
logic-delete-value: 1
logic-not-delete-value: 0
2.3 创建生成类
根据mybatis-plus的版本不同,生成代码会有所区别。
2.3.1 mybatis-plus 3.4版本
package com.ywz.common;
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.NamingStrategy;
import java.util.ArrayList;
/**
* 类描述 -> 代码生成器
*
* @Author: ywz
* @Date: 2024/10/15
*/
public class CodeGenerator {
// 项目跟路径
private static final String PROJECT_PATH = System.getProperty("user.dir");
// 代码生成路径,根据实际项目名更改
private static final String MODULE_NAME = PROJECT_PATH + "/src/main/java";
// 数据库连接
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/ywz_db?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
private static final String USER_NAME = "root";
private static final String PASSWORD = "root";
// 生成包路径
private static final String PACKAGE_NAME = "com.ywz.project.base";
// 生成表数组
private static final String[] TABLE_NAMES = {"t_sys_user", "t_sys_role", "t_sys_user_role", "t_sys_permission"
, "t_sys_role_permission", "t_sys_menu", "t_sys_login_log", "t_sys_oper_log", "t_china"};
// 是否启动
private static final boolean START = false;
public static void main(String[] args) {
if (!START)
return;
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(MODULE_NAME);
gc.setFileOverride(true);// 是否覆盖以前文件
gc.setOpen(false);// 是否打开生成目录
gc.setAuthor("ywz");// 设置项目作者名称
gc.setIdType(IdType.AUTO);// 设置主键策略
gc.setBaseResultMap(true);// 生成基本ResultMap
gc.setBaseColumnList(true);// 生成基本ColumnList
gc.setServiceName("%sService");// 去掉服务默认前缀
// 设置时间类型,默认是LocalDate与LocalDateTime类型
// gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true); // 实体类添加swagger注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DATABASE_URL);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(USER_NAME);
dsc.setPassword(PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(PACKAGE_NAME);
pc.setMapper("mapper");
pc.setXml("mapper.xml");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig sc = new StrategyConfig();
sc.setNaming(NamingStrategy.underline_to_camel);
sc.setColumnNaming(NamingStrategy.underline_to_camel);
sc.setEntityLombokModel(true); // 自动lombok
sc.setRestControllerStyle(true);
sc.setControllerMappingHyphenStyle(true);
sc.setLogicDeleteFieldName("deleted");// 设置逻辑删除
//设置自动填充配置
TableFill gmt_create = new TableFill("create_time", FieldFill.INSERT);
TableFill gmt_modified = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmt_create);
tableFills.add(gmt_modified);
sc.setTableFillList(tableFills);
//乐观锁
sc.setVersionFieldName("version");
sc.setRestControllerStyle(true);//驼峰命名
// sc.setTablePrefix("tbl_"); 设置表名前缀
// 设置要生成的表名
sc.setInclude(TABLE_NAMES);
mpg.setStrategy(sc);
// 生成代码
mpg.execute();
}
}
2.3.2 mybatis-plus 3.5版本
此生成代码使用freemarker模版引擎。需要更换模版依赖包。
<!-- 将此处的依赖更改为下面的freemarker依赖包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3</version>
</dependency>
-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.34</version>
</dependency>
package com.ywz.common;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
* 类描述 -> mybatis-plus代码生成器 (新版本mybatis-plus版本3.5.1以上)
*
* @Author: ywz
* @Date: 2025/02/07
*/
public class MybatisPlusCodeGenerator {
public static final String URL = "jdbc:mysql://localhost:3306/saas-crm-master?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true";
public static final String USERNAME = "root";
public static final String PASSWORD = "root";
// 生成表数组
private static final String[] TABLE_NAMES = {"t_sys_tenement"
};
// 是否启动
private static final boolean START = true;
public static void main(String[] args) {
if (!START)
return;
FastAutoGenerator.create(URL, USERNAME, PASSWORD)
.globalConfig(builder -> {
builder.author("游王子og") // 设置作者
.outputDir("./code"); // 输出目录
})
.packageConfig(builder -> {
builder.parent("com.ywz") // 设置父包名
.entity("entity") // 设置实体类包名
.mapper("mapper") // 设置 Mapper 接口包名
.service("service") // 设置 Service 接口包名
.serviceImpl("service.impl") // 设置 Service 实现类包名
.xml("mappers"); // 设置 Mapper XML 文件包名
})
.strategyConfig(builder -> {
builder.addInclude(TABLE_NAMES) // 设置需要生成的表名
.entityBuilder()
.enableLombok() // 启用 Lombok
.enableTableFieldAnnotation() // 启用字段注解
.controllerBuilder()
.enableRestStyle(); // 启用 REST 风格
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用 Freemarker 模板引擎
.execute(); // 执行生成
}
}
三、运行程序
在控制台中输入要创建的表:
回车确认:
查看生成结果: