MyBatisPlus代码生成器自定义FreemarkerEngine

前言

MyBatisPlus:AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller
等各个模块的代码,极大的提升了开发效率。

很多时候上面生成的代码不能满足开发需求,在自定义模板的同时,我们也会自定义模板引擎,这里使用 Freemarker模板引擎。

MyBatisPlus代码生成器官方简介

配置

pom.xml配置

1
2
3
4
5

<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>

自定义模板引擎类

CustomFreemarkerTemplateEngine

AutoGenerator配置

1
2
3
4
5
6
7
8
9
public class MpGeneratorDemo {
public void generator() {
AutoGenerator mpg = new AutoGenerator();
/**省略其他配置*/
CustomFreemarkerTemplateEngine templateEngine = new CustomFreemarkerTemplateEngine(config);
/*配置模板引擎的属性,比如自定义的config,构造时传参*/
mpg.setTemplateEngine(templateEngine);
}
}

FreemarkerEngine

继承 AbstractTemplateEngine

这里有三个属性

  1. configurationfreemarker配置,可以获取模板并操作模板
  2. zipOutputStream:导出ZIP文件的输出流
  3. config:自定义配置,可以控制是否输出ZIP文件、控制自定义模板属性等等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

@Slf4j
public class CustomFreemarkerTemplateEngine extends AbstractTemplateEngine {
/**
* freemarker 配置
*/
private Configuration configuration;
/**
* zip 输出流
*/
@Setter
private ZipOutputStream zipOutputStream;
/**
* 自定义配置
*/
private final CodeGeneratorConfig config;

/**
* 初始化
*
* @param config 自定义配置
*/
public CustomFreemarkerTemplateEngine(CodeGeneratorConfig config) {
this.config = config;
}

@Override
public CustomFreemarkerTemplateEngine init(ConfigBuilder configBuilder) {
super.init(configBuilder);
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding(ConstVal.UTF8);
configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
return this;
}

@Override
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
Template template = configuration.getTemplate(templatePath);
/**生成模板操作***************************/
}

/**
* 获取模板路径<br>
* 在配置时,一般不配置 .ftl 文件,这是 Freemarker 模板的习惯,所以这里要在路径上添加 .ftl
*
* @param filePath 模板路径
* @return 模板真实路径
*/
@Override
public String templateFilePath(String filePath) {
return filePath + ".ftl";
}

@Override
public Map<String, Object> getObjectMap(TableInfo tableInfo) {
Map<String, Object> objectMap = super.getObjectMap(tableInfo);
/*****************************/
return objectMap;
}
}

writer模板生成方法

当前方法有三个参数:

  1. 模板的参数Map
    • 当前属性是 AbstractTemplateEngine中配置了一部分
    • 自定义模板引擎中自定义一部分
  2. 模板路径
  3. 输出文件路径

模板生成方法主要做了3件事:

  1. 根据模板路径获取模板
    • 模板路径是由配置路径和templateFilePath方法创建的
    • templateFilePath方法是参入配置路径,返回实际模板路径
  2. 生成模板
  3. 写入ZIP文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class CustomFreemarkerTemplateEngine extends AbstractTemplateEngine {
/************************************/
@Override
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
Template template = configuration.getTemplate(templatePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
}
log.debug("模板:" + templatePath + "; 文件:" + outputFile);
if (config.getUseZip()) {
InputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
zipOutputStream.putNextEntry(new ZipEntry(outputFile.replace(config.getOutPutDir(), "")));
byte[] buff = new byte[4096];
int len;
try {
inputStream = new FileInputStream(outputFile);
/*读取文件*/
bufferedInputStream = new BufferedInputStream(inputStream);
/*判断:当前已经传递的数据大小+当前已有的长度,小于总长度时,*/
while ((len = bufferedInputStream.read(buff)) != -1) {
zipOutputStream.write(buff, 0, len);
}
} catch (Exception e) {
log.error("代码生成器:输出ZIP错误:模板 :{}; 文件:{}", templatePath, outputFile);
log.error("代码生成器:输出ZIP错误", e);
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(bufferedInputStream);
}
}
}
/************************************/
}

getObjectMap获取模板参数方法

  1. 当前方法只有一个参数TableInfo,顾名思义,就是单表的信息。
  2. TableInfo主要包括表结构、主要的Class Entity、Mapper、Mapper XML、Service、Controller
  3. 如果在 AutoGenerator 中配置了策略,这里就会得到执行策略后的名字。

我在这里配置了一个自己的CustomTableInfo(附录),除了自带的信息外,好包含了 dtoName、voName、convertName等等。

下面是一段配置的作用是,传入模板参数 activeCrud,当前参数可以在模板中判断是否生成 crud代码(需要模板中有相关代码):

1
2
3
4
5
6
7
8
9
  public class CustomFreemarkerTemplateEngine extends AbstractTemplateEngine {
@Override
public Map<String, Object> getObjectMap(TableInfo tableInfo) {
Map<String, Object> objectMap = super.getObjectMap(tableInfo);
/*使用增删改查*/
objectMap.put("activeCrud", config.getActiveCrud());
return objectMap;
}
}

我在 freemarker自定义模板中,就可以使用

附录

CodeGeneratorFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package com.gt.code.generator.factory;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
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.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.gt.code.generator.config.CodeGeneratorConfig;
import com.gt.code.generator.config.CodeGeneratorDbConfig;
import com.gt.code.generator.config.CodeGeneratorEnumVal;
import com.gt.code.generator.config.CodeGeneratorVal;
import com.gt.code.generator.util.template.CustomFreemarkerTemplateEngine;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;
import java.util.zip.ZipOutputStream;

/**
* 生成代码工厂<br>
*
* @author maxzhao
* @date 2021-08-27
*/
public class CodeGeneratorFactory {
/**
* 自动填充
*/
private static final List<TableFill> TABLE_FILL_LIST = Arrays.asList(
new TableFill("createTime", FieldFill.INSERT),
new TableFill("updateTime", FieldFill.UPDATE),
new TableFill("delStatus", FieldFill.INSERT_UPDATE));

private CodeGeneratorFactory() {
}

public static byte[] generate(CodeGeneratorConfig config) {
AutoGenerator mpg = new AutoGenerator();
CodeGeneratorDbConfig dbConfig = config.getDbConfig();
/*输出路径*/
String outPutDir = config.getFullOutPutDir();
//region 注入配置
mpg.setCfg(configInjection(config));
//endregion
//region 数据源配置
DataSourceConfig dataSource = dbConfig.generatorDataSourceConfig();
if (dataSource.getDbType() == DbType.ORACLE) {
dataSource.setTypeConvert(new OracleTypeConvert() {
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
if (fieldType.toLowerCase(Locale.ROOT).matches("")) {

}
return super.processTypeConvert(globalConfig, fieldType);
}
});
}
mpg.setDataSource(dataSource);
//endregion
//region 表策略配置
StrategyConfig strategy = new StrategyConfig();
/*驼峰*/
strategy.setNaming(NamingStrategy.underline_to_camel);
/*驼峰*/
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
/*使用 lombok*/
strategy.setEntityLombokModel(true);
/*默认使用 restfull风格*/
strategy.setRestControllerStyle(true);
/*标*/
strategy.setInclude(config.getTablesNames());
/*驼峰转连字符串*/
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(config.getTablePrefix());
/*字段添加 @TableField*/
strategy.setEntityTableFieldAnnotationEnable(true);
strategy.setTableFillList(TABLE_FILL_LIST);
mpg.setStrategy(strategy);
//endregion
//region 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(config.getModuleName());
pc.setParent(config.getParentPackage());
/*设置 controller 文件 包名*/
pc.setController(CodeGeneratorEnumVal.CONTROLLER.getPackageName());
/*设置 xml 文件 包名*/
pc.setXml("mapper");
/*设置 entity 文件 包名*/
pc.setEntity("model.entity");
pc.setXml("mapper");
mpg.setPackageInfo(pc);
//endregion
//region 模板配置
TemplateConfig templateConfig = new TemplateConfig()
.setEntity(CodeGeneratorEnumVal.ENTITY.getTemplate())
.setController(CodeGeneratorEnumVal.CONTROLLER.getTemplate())
.setService(CodeGeneratorEnumVal.SERVICE.getTemplate())
.setServiceImpl(CodeGeneratorEnumVal.SERVICE_IMPL.getTemplate())
.setMapper(CodeGeneratorEnumVal.MAPPER.getTemplate())
.setXml(CodeGeneratorEnumVal.TEMPLATE_XML.getTemplate());
mpg.setTemplate(templateConfig);
//endregion
//region 全局配置
/*默认使用雪花算法*/
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(outPutDir);
gc.setAuthor(config.getAuthor());
gc.setOpen(false);
/*默认不覆盖,如果文件存在,将不会再生成,配置true就是覆盖*/
gc.setFileOverride(true);
/*配置 swagger2*/
gc.setSwagger2(config.getSwagger2());
/*开启 ActiveRecord 模式*/
gc.setActiveRecord(config.getActiveRecord());
mpg.setGlobalConfig(gc);

//endregion
//region 模板引擎
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
CustomFreemarkerTemplateEngine templateEngine = new CustomFreemarkerTemplateEngine(config);
ByteArrayOutputStream outputStream = null;
ZipOutputStream zip = null;
if (config.getUseZip()) {
/*下载zip文件 字节输出流*/
outputStream = new ByteArrayOutputStream();
zip = new ZipOutputStream(outputStream);
templateEngine.setZipOutputStream(zip);
/*下载zip ,会覆盖文件*/
gc.setFileOverride(true);
}
mpg.setTemplateEngine(templateEngine);
//endregion
mpg.execute();
if (config.getUseZip()) {
/*获取结果*/
//等同于自己写判断然后关闭
IOUtils.closeQuietly(zip);
return outputStream != null ? outputStream.toByteArray() : null;
}
return null;
}

/**
* 添加自动填充
*
* @param tableFill 新的自动填充
*/
public static void addTableFill(TableFill tableFill) {
TABLE_FILL_LIST.add(tableFill);
}

/**
* 配置自定义参数/属性
*
* @param config 配置信息
*/
private static InjectionConfig configInjection(CodeGeneratorConfig config) {
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
String controllerPackage = this.getConfig().getPackageInfo().get("Controller");
this.getConfig().getPackageInfo().put("Dto", controllerPackage + ".dto");
this.getConfig().getPackageInfo().put("Params", controllerPackage + ".Params");
this.getConfig().getPackageInfo().put("Vo", controllerPackage + ".vo");
this.getConfig().getPackageInfo().put("Convert", controllerPackage.substring(0, controllerPackage.lastIndexOf(CodeGeneratorEnumVal.CONTROLLER.getPackageName())) + CodeGeneratorEnumVal.CONVERT.getPackageName());
String xmlPath = this.getConfig().getPathInfo().get("xml_path");
/*修改 xml 生成路径*/
this.getConfig().getPathInfo().put("xml_path", xmlPath.replace(CodeGeneratorVal.JAVA_SOURCE_PATH, CodeGeneratorVal.XML_SOURCE_PATH));
Map<String, Object> map = new HashMap<>(4);
/*自定义cfg引用*/
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<>();
/*dto 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.DTO));
/*params 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.PARAMS));
/*vo 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.VO));
/*判断是否使用 mapstruct convert*/
if ((config.getUseConvert() != null && config.getUseConvert())
/*增删查改时使用*/
|| (config.getActiveCrud() != null && config.getActiveCrud())) {
/*convert 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.CONVERT));
}
/*使用增删查改*/
if (config.getActiveCrud() != null && config.getActiveCrud()) {
/*exception 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.EXCEPTION));
/*exception enum 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.EXCEPTION_ENUM));
/*exception handler 模板*/
focList.add(convertFileOutConfig(config, CodeGeneratorEnumVal.EXCEPTION_HANDLER));
}
cfg.setFileOutConfigList(focList);
return cfg;
}

/**
* 加载文件输出配置
*
* @param config 配置
* @param enumVal 模板
* @return mybatis plus 文件输出配置
*/
private static FileOutConfig convertFileOutConfig(CodeGeneratorConfig config, CodeGeneratorEnumVal enumVal) {
return new FileOutConfig(enumVal.getTemplate()) {
@Override
public String outputFile(TableInfo tableInfo) {
/*指定模板生,自定义生成文件到哪个地方*/
return config.getModuleOutPutDir() + File.separator +
enumVal.getPackageName().replace(".", File.separator) +
File.separator +
String.format(enumVal.getClassName(), tableInfo.getEntityName()) + StringPool.DOT_JAVA;
}
};
}
}

CustomFreemarkerTemplateEngine

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package com.gt.code.generator.util.template;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.gt.code.generator.config.CodeGeneratorConfig;
import com.gt.code.generator.config.CodeGeneratorEnumVal;
import com.gt.code.generator.util.CustomTableInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* 自定义 Freemarker 模板引擎
*
* @author maxzhao
* @date 2021-08-28 08:36
*/
@Slf4j
public class CustomFreemarkerTemplateEngine extends AbstractTemplateEngine {
/**
* freemarker 配置
*/
private Configuration configuration;
/**
* zip 输出流
*/
@Setter
private ZipOutputStream zipOutputStream;
/**
* 自定义配置
*/
private final CodeGeneratorConfig config;

/**
* 初始化
*
* @param config 自定义配置
*/
public CustomFreemarkerTemplateEngine(CodeGeneratorConfig config) {
this.config = config;
}

@Override
public CustomFreemarkerTemplateEngine init(ConfigBuilder configBuilder) {
super.init(configBuilder);
configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
configuration.setDefaultEncoding(ConstVal.UTF8);
configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
return this;
}


@Override
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
Template template = configuration.getTemplate(templatePath);
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
}
log.debug("模板:" + templatePath + "; 文件:" + outputFile);
if (config.getUseZip()) {
InputStream inputStream = null;
BufferedInputStream bufferedInputStream = null;
zipOutputStream.putNextEntry(new ZipEntry(outputFile.replace(config.getOutPutDir(), "")));
byte[] buff = new byte[4096];
int len;
try {
inputStream = new FileInputStream(outputFile);
/*读取文件*/
bufferedInputStream = new BufferedInputStream(inputStream);
/*判断:当前已经传递的数据大小+当前已有的长度,小于总长度时,*/
while ((len = bufferedInputStream.read(buff)) != -1) {
zipOutputStream.write(buff, 0, len);
}
} catch (Exception e) {
log.error("代码生成器:输出ZIP错误:模板 :{}; 文件:{}", templatePath, outputFile);
log.error("代码生成器:输出ZIP错误", e);
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(bufferedInputStream);
}
}
}


/**
* 获取模板路径<br>
* 在配置时,一般不配置 .ftl 文件,这是 Freemarker 模板的习惯,所以这里要在路径上添加 .ftl
*
* @param filePath 模板路径
* @return 模板真实路径
*/
@Override
public String templateFilePath(String filePath) {
return filePath + ".ftl";
}

@Override
public Map<String, Object> getObjectMap(TableInfo tableInfo) {
Map<String, Object> objectMap = super.getObjectMap(tableInfo);
/*获取类 Package*/
Map<String, String> packageInfo = super.getConfigBuilder().getPackageInfo();
String controllerPackage = packageInfo.get("Controller");
/*基础 package*/
String basePackage = controllerPackage.substring(0, controllerPackage.lastIndexOf(CodeGeneratorEnumVal.CONTROLLER.getPackageName()));
packageInfo.put("basePackage", basePackage);
/*自定义表数据*/
CustomTableInfo customTableInfo = CustomTableInfo.getInstance(tableInfo);
/*使用增删改查*/
objectMap.put("activeCrud", config.getActiveCrud());
if (config.getActiveCrud() != null && config.getActiveCrud()) {
/*使用增删改查时,添加代码引入*/
packageInfo.put("ExceptionHandler", basePackage + "exception.handler");
packageInfo.put("Exception", basePackage + "exception");
packageInfo.put("ExceptionEnum", basePackage + "exception");
customTableInfo.initImportPackage(packageInfo);
}

/*每个类的 package*/
objectMap.put("packageInfo", packageInfo);
/*自定义表数据*/
objectMap.put("table", customTableInfo);
return objectMap;
}
}

CustomTableInfo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.gt.code.generator.util;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.gt.code.generator.config.CodeGeneratorEnumVal;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.*;


/**
* 自定义表配置
*
* @author maxzhao
* @date 2021-08-29 10:47
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
public class CustomTableInfo extends TableInfo {
/**
* 主键类型,默认为 String
*/
private String idTypeClassName;
private String dtoName;
private String paramsName;
private String voName;
private String convertName;
private String serviceBeanName;
private String mapperBeanName;
private String convertBeanName;
/**
* 异常类名
*/
private String exceptionName;
/**
* 异常枚举
*/
private String exceptionEnumName;
/**
* 异常处理类名
*/
private String exceptionHandlerName;
/**
* 使用 crud 时的 CONTROLLER 引入
*/
private final Set<String> apiImportPackages = new HashSet<>();
/**
* 使用 crud 时的 SERVICE 接口引入
*/
private final Set<String> serviceImportPackages = new HashSet<>();
/**
* 使用 crud 时的 SERVICE 实现引入
*/
private final Set<String> serviceImplImportPackages = new HashSet<>();
/**
* 使用 crud 时的 通用 实现引入
*/
private final Set<String> crudImplImportPackages = new HashSet<>();

public CustomTableInfo(TableInfo tableInfo) {
this.setConvert(tableInfo.isConvert());
this.setEntityName(tableInfo.getEntityName());
List<TableField> fields = tableInfo.getFields();
this.setFields(fields);
for (TableField field : fields) {
if (field.isKeyFlag()) {
this.idTypeClassName = field.getColumnType().getType();
}
}
if (!StringUtils.hasText(this.idTypeClassName)) {
this.idTypeClassName = "String";
}
this.getImportPackages().addAll(tableInfo.getImportPackages());
this.setName(tableInfo.getName());
this.setComment(tableInfo.getComment());
this.setEntityName(tableInfo.getEntityName());
this.setMapperName(tableInfo.getMapperName());
this.setXmlName(tableInfo.getXmlName());
this.setServiceName(tableInfo.getServiceName());
this.setServiceImplName(tableInfo.getServiceImplName());
this.setControllerName(tableInfo.getControllerName());
this.setCommonFields(tableInfo.getCommonFields());
this.setFieldNames(tableInfo.getFieldNames());


}


public static CustomTableInfo getInstance(TableInfo tableInfo) {
CustomTableInfo customTableInfo = new CustomTableInfo(tableInfo);

customTableInfo.setDtoName(String.format(CodeGeneratorEnumVal.DTO.getClassName(), tableInfo.getEntityName()));
customTableInfo.setParamsName(String.format(CodeGeneratorEnumVal.PARAMS.getClassName(), tableInfo.getEntityName()));
customTableInfo.setVoName(String.format(CodeGeneratorEnumVal.VO.getClassName(), tableInfo.getEntityName()));
customTableInfo.setConvertName(String.format(CodeGeneratorEnumVal.CONVERT.getClassName(), tableInfo.getEntityName()));

String serviceBeanName = customTableInfo.getServiceName().substring(1);
serviceBeanName = serviceBeanName.substring(0, 1).toLowerCase() + serviceBeanName.substring(1);
customTableInfo.setServiceBeanName(serviceBeanName);
String mapperBeanName = customTableInfo.getMapperName();
mapperBeanName = mapperBeanName.substring(0, 1).toLowerCase() + mapperBeanName.substring(1);
customTableInfo.setMapperBeanName(mapperBeanName);
customTableInfo.setConvertBeanName(customTableInfo.getConvertName().substring(0, 1).toLowerCase(Locale.ROOT) +
customTableInfo.getConvertName().substring(1));

/*异常类名 */
customTableInfo.setExceptionName(String.format(CodeGeneratorEnumVal.EXCEPTION.getClassName(), tableInfo.getEntityName()));
customTableInfo.setExceptionEnumName(String.format(CodeGeneratorEnumVal.EXCEPTION_ENUM.getClassName(), tableInfo.getEntityName()));
customTableInfo.setExceptionHandlerName(String.format(CodeGeneratorEnumVal.EXCEPTION_HANDLER.getClassName(), tableInfo.getEntityName()));
return customTableInfo;
}

/**
* 初始化导入依赖
*
* @param packageInfo 所有的 package
*/
public void initImportPackage(Map<String, String> packageInfo) {
apiImportPackages.add(java.util.List.class.getCanonicalName());
apiImportPackages.add(org.springframework.http.ResponseEntity.class.getCanonicalName());

serviceImportPackages.add(java.util.List.class.getCanonicalName());
serviceImplImportPackages.add(java.util.List.class.getCanonicalName());
serviceImplImportPackages.add(packageInfo.get("Convert") + StringPool.DOT + this.getConvertName());
serviceImplImportPackages.add(packageInfo.get("Exception") + StringPool.DOT + this.getExceptionName());
serviceImplImportPackages.add(packageInfo.get("ExceptionEnum") + StringPool.DOT + this.getExceptionEnumName());
serviceImplImportPackages.add(packageInfo.get("ExceptionHandler") + StringPool.DOT + this.getExceptionHandlerName());
serviceImplImportPackages.add(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper.class.getCanonicalName());


crudImplImportPackages.add(com.baomidou.mybatisplus.core.metadata.IPage.class.getCanonicalName());
crudImplImportPackages.add(com.baomidou.mybatisplus.extension.plugins.pagination.Page.class.getCanonicalName());
crudImplImportPackages.add(packageInfo.get("Dto") + StringPool.DOT + this.dtoName);
crudImplImportPackages.add(packageInfo.get("Params") + StringPool.DOT + this.paramsName);
crudImplImportPackages.add(packageInfo.get("Vo") + StringPool.DOT + this.voName);
crudImplImportPackages.add(packageInfo.get("Entity") + StringPool.DOT + this.getEntityName());

}
}

本文地址: https://github.com/maxzhao-it/blog/post/15751/