MybatisPlus代码生成器实现只覆盖指定文件
问题
在使用MybatisPlus的过程中如果数据库结构发生了改变(增加或者删除了字段),应该怎么办?
- 重新运行代码生成器?
- 手动去Entity里面修改?
第一个办法在项目还没开始的时候是没问题的,毕竟控制器和服务里面都没有代码,只要把
全局策略 globalConfig 配置
中的
fileOverride
设置为
true
就可以直接覆盖了,但是如果已经写了一部分就不行了,因为代码生成器覆盖的话默认会覆盖所有的文件,而在
service
和
mapper
这些文件里面已经有了自己写的代码就不能这样直接覆盖。
第二个办法应该就是大多数人选择的办法了,每次改了数据库就手动去改一下Entity,这样是没有问题的。但是对于一个要优雅写代码的人肯定是不能接受的,都有了生成器我为什么还要去手动写呢?
解决
终于在我的强迫症驱使下我还是找到了可以设置覆盖哪些文件的办法,先来看看官方文档给的生成示例:
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <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 + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("密码");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.baomidou.ant");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.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 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
进入最后一行的
mpg.execute()
方法可以看到:
public void execute() {
logger.debug("==========================准备生成文件...==========================");
if (null == this.config) {
this.config = new ConfigBuilder(this.packageInfo, this.dataSource, this.strategy, this.template, this.globalConfig);
if (null != this.injectionConfig) {
this.injectionConfig.setConfig(this.config);
}
}
if (null == this.templateEngine) {
this.templateEngine = new VelocityTemplateEngine();
}
this.templateEngine.init(this.pretreatmentConfigBuilder(this.config)).mkdirs().batchOutput().open();
logger.debug("==========================文件生成完成!!!==========================");
}
多找一找就会发现生成文件的方法就是
batchOutput()
,继续跟进去:
public AbstractTemplateEngine batchOutput() {
try {
List<TableInfo> tableInfoList = this.getConfigBuilder().getTableInfoList();
Iterator var2 = tableInfoList.iterator();
while(var2.hasNext()) {
TableInfo tableInfo = (TableInfo)var2.next();
Map<String, Object> objectMap = this.getObjectMap(tableInfo);
Map<String, String> pathInfo = this.getConfigBuilder().getPathInfo();
TemplateConfig template = this.getConfigBuilder().getTemplate();
InjectionConfig injectionConfig = this.getConfigBuilder().getInjectionConfig();
if (null != injectionConfig) {
injectionConfig.initTableMap(tableInfo);
objectMap.put("cfg", injectionConfig.getMap());
List<FileOutConfig> focList = injectionConfig.getFileOutConfigList();
if (CollectionUtils.isNotEmpty(focList)) {
Iterator var9 = focList.iterator();
while(var9.hasNext()) {
FileOutConfig foc = (FileOutConfig)var9.next();
if (this.isCreate(FileType.OTHER, foc.outputFile(tableInfo))) {
this.writer(objectMap, foc.getTemplatePath(), foc.outputFile(tableInfo));
}
}
}
}
String entityName = tableInfo.getEntityName();
String controllerFile;
if (null != entityName && null != pathInfo.get("entity_path")) {
controllerFile = String.format((String)pathInfo.get("entity_path") + File.separator + "%s" + this.suffixJavaOrKt(), entityName);
if (this.isCreate(FileType.ENTITY, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getEntity(this.getConfigBuilder().getGlobalConfig().isKotlin())), controllerFile);
}
}
if (null != tableInfo.getMapperName() && null != pathInfo.get("mapper_path")) {
controllerFile = String.format((String)pathInfo.get("mapper_path") + File.separator + tableInfo.getMapperName() + this.suffixJavaOrKt(), entityName);
if (this.isCreate(FileType.MAPPER, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getMapper()), controllerFile);
}
}
if (null != tableInfo.getXmlName() && null != pathInfo.get("xml_path")) {
controllerFile = String.format((String)pathInfo.get("xml_path") + File.separator + tableInfo.getXmlName() + ".xml", entityName);
if (this.isCreate(FileType.XML, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getXml()), controllerFile);
}
}
if (null != tableInfo.getServiceName() && null != pathInfo.get("service_path")) {
controllerFile = String.format((String)pathInfo.get("service_path") + File.separator + tableInfo.getServiceName() + this.suffixJavaOrKt(), entityName);
if (this.isCreate(FileType.SERVICE, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getService()), controllerFile);
}
}
if (null != tableInfo.getServiceImplName() && null != pathInfo.get("service_impl_path")) {
controllerFile = String.format((String)pathInfo.get("service_impl_path") + File.separator + tableInfo.getServiceImplName() + this.suffixJavaOrKt(), entityName);
if (this.isCreate(FileType.SERVICE_IMPL, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getServiceImpl()), controllerFile);
}
}
if (null != tableInfo.getControllerName() && null != pathInfo.get("controller_path")) {
controllerFile = String.format((String)pathInfo.get("controller_path") + File.separator + tableInfo.getControllerName() + this.suffixJavaOrKt(), entityName);
if (this.isCreate(FileType.CONTROLLER, controllerFile)) {
this.writer(objectMap, this.templateFilePath(template.getController()), controllerFile);
}
}
}
} catch (Exception var11) {
logger.error("无法创建文件,请检查配置信息!", var11);
}
return this;
}
这个方法里面有好几个if判断就是判断是否写文件的,仔细看外层的
if
都有默认值所以直接就能进入,所以是否写文件都是通过
this.isCreate
这个函数来确定的,点进去:
protected boolean isCreate(FileType fileType, String filePath) {
ConfigBuilder cb = this.getConfigBuilder();
InjectionConfig ic = cb.getInjectionConfig();
//判断是否自定义isCreate方法,优先使用自定义的
if (null != ic && null != ic.getFileCreate()) {
return ic.getFileCreate().isCreate(cb, fileType, filePath);
} else {
File file = new File(filePath);
boolean exist = file.exists();
if (!exist) {
file.getParentFile().mkdirs();
}
return !exist || this.getConfigBuilder().getGlobalConfig().isFileOverride();
}
}
判断是否注入过自定义配置并且自定义配置里面有
fileCreate
属性,条件成立则根据
fileCreate
对象的
isCreate()
方法返回值来判断是否需要写文件。
看到这里应该就能大概知道怎么控制哪些文件覆盖哪些文件不覆盖了,只需要注入一个自定义的配置,并在自定义的配置中实现自定义逻辑就可以了。
在官方的示例里面其实有一段注释了的代码就是做这个的:
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
比如我需要只覆盖Entity,其他的只有不存在的时候才创建可以这样写:
cfg.setFileCreate((configBuilder, fileType, filePath) -> {
//如果是Entity则直接返回true表示写文件
if (fileType == FileType.ENTITY) {
return true;
}
//否则先判断文件是否存在
File file = new File(filePath);
boolean exist = file.exists();
if (!exist) {
file.getParentFile().mkdirs();
}
//文件不存在或者全局配置的fileOverride为true才写文件
return !exist || configBuilder.getGlobalConfig().isFileOverride();
});
这样就实现了每次运行代码生成器如果文件存在就只会覆盖Entity了,怎么改数据库结构都可以一键完成Entity修改。