Mybatis-Plus 代码生成器
1. 旧版
1.1 引用pom
<!-- JDK 1.8 / 11 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- MybatisPlus代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
1.2 示例类
package com.adc.da.mp;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {
private static String moduleName = "demo"; //模块名称 spaceTime
private static String author = "ld"; //作者
private static String projectPath = "D:\\A-Project\\A-L\\Demo\\P1Server\\adc-da-demo"; //代码生成路径
private static String[] tableNames = new String[] {"user","demo"}; //需要生成代码的数据库表名
private static String[] tablePrefix = new String[] { "V_", "T_" }; //表前缀
private static String url = "jdbc:mysql://localhost:3308/junw"; //数据源url
private static String username = "root"; //数据源连接用户名
private static String password = "123456"; //数据源连接密码
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setIdType(IdType.UUID);
gc.setDateType(DateType.ONLY_DATE);
gc.setFileOverride(true);
gc.setActiveRecord(true);
gc.setControllerName("%sEOController");
gc.setServiceName("I%sEOService");
gc.setServiceImplName("%sEOServiceImpl");
// gc.setEntityName("%sEO");
gc.setMapperName("%sEODao");
gc.setXmlName("%sEOMapper");
// gc.setEnableCache(true);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(moduleName);
pc.setParent("com.adc.da");
pc.setMapper("dao");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// Map<String, Object> map = new HashMap<>();
// map.put("restPath", "${restPath}");
// this.setMap(map);
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
String templatePath2 = "/templates/entity.java.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! mysql starrocks
return projectPath + "/src/main/resources/mybatis/mapper/" + moduleName+ "/mysql/" + tableInfo.getEntityName() + "EOMapper" +
StringPool.DOT_XML;
}
});
focList.add(new FileOutConfig(templatePath2) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/adc/da/" + moduleName + "/entity/" + tableInfo.getEntityName() + "EO" +
StringPool.DOT_JAVA;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setEntity(null);
// templateConfig.setService(null);
// templateConfig.setServiceImpl(null);
// templateConfig.setController(null);
// templateConfig.setMapper(null);
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setControllerMappingHyphenStyle(false);
strategy.setEntityTableFieldAnnotationEnable(true);
strategy.setEntityColumnConstant(true);
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setEntitySerialVersionUID(true);
strategy.setInclude(tableNames);
// 公共父类
strategy.setSuperControllerClass("com.adc.da.mp.base.BaseController");
// 写于父类中的公共字段
strategy.setSuperServiceClass("com.adc.da.mp.base.IBaseService");
strategy.setSuperEntityClass("com.adc.da.mp.base.BaseEntity");
// strategy.setSuperEntityColumns("CREATER_ID", "CREATER_TIME", "UPDATER_ID", "UPDATER_TIME");
strategy.setRestControllerStyle(true);
// strategy.setSuperEntityColumns("id");
// strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(tablePrefix);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
}
2. 新版
2.1 引用pom
<!-- JDK 17 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
<!-- MybatisPlus代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
<scope>compile</scope>
</dependency>
2.2 示例类
package my.junw.usercenter;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.nio.file.Paths;
import java.util.Collections;
public class CodeGenerator {
private static String moduleName = ""; //模块名称 spaceTime
private static String author = "ld"; //作者
private static String projectPath = "D:\\A-Project\\A-ZSXQ\\Junw-UserCenter\\junw-user-center-server"; //代码生成路径
private static String[] tableNames = new String[] {"user"}; //需要生成代码的数据库表名
private static String[] tablePrefix = new String[] { "V_", "T_"}; //表前缀
private static String url = "jdbc:mysql://localhost:3308/junw"; //数据源url
private static String username = "root"; //数据源连接用户名
private static String password = "123456"; //数据源连接密码
public static void main(String[] args) {
FastAutoGenerator.create(url, username, password)
.globalConfig(builder -> builder
.author(author)
.outputDir(Paths.get(projectPath) + "/" + moduleName + "/src/main/java")
.commentDate("yyyy-MM-dd")
.disableOpenDir()
// .enableSwagger()
.dateType(DateType.ONLY_DATE)
)
.packageConfig(builder -> builder
// .moduleName("")
.parent("my.junw.usercenter")
.entity("entity")
.mapper("dao")
.service("service")
.serviceImpl("service.Impl")
.controller("controller")
.pathInfo(Collections.singletonMap(OutputFile.xml,projectPath + "/src/main/resources/mybatis/mapper/" + moduleName+ "/mysql/" ))
)
.strategyConfig(builder -> builder
.addInclude(tableNames) // 表名s
.addTablePrefix(tablePrefix) // 表名-前缀s
.entityBuilder() // --> 实体类
.enableLombok() // 开启 Lombok 模型
.enableChainModel() // 开启链式模型
.enableTableFieldAnnotation() // 启用字段注解
.naming(NamingStrategy.underline_to_camel)
.enableColumnConstant() // 开启生成字段常量
.columnNaming(NamingStrategy.underline_to_camel)
.enableFileOverride() // 覆盖已生成文件
// .idType(IdType.ASSIGN_UUID)
.formatFileName("%sEO")
.controllerBuilder()// --> 控制器
.enableHyphenStyle()
.enableRestStyle()
.formatFileName("%sEOController")
.enableFileOverride()
.serviceBuilder()// --> 业务层
.formatServiceFileName("I%sEOService")
.formatServiceImplFileName("%sEOServiceImpl")
.enableFileOverride()
.mapperBuilder()
.superClass(BaseMapper.class)
.enableBaseResultMap()
.enableBaseColumnList()
.formatMapperFileName("%sEODao")
.formatXmlFileName("%sEOMapper")
.enableFileOverride()
)
.templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果