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
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.stark37125.core.base.cons.CommonField;
import com.stark37125.core.base.controller.MyController;
import com.stark37125.core.base.mapper.MyMapper;
import com.stark37125.core.base.model.entity.MyEntity;
import com.stark37125.core.base.service.MyService;
import com.stark37125.core.base.service.impl.MyServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author shuzhuo
*/
public class CodeGenerator {

private static Pattern humpPattern = Pattern.compile("[A-Z]");

public static String humpToLine(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();

while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}

matcher.appendTail(sb);
return sb.toString();
}


static String[] commonField = new String[]{
CodeGenerator.humpToLine(CommonField.CREATE_USER),
CodeGenerator.humpToLine(CommonField.DELETE_FLAG),
CodeGenerator.humpToLine(CommonField.UPDATE_USER),
CodeGenerator.humpToLine(CommonField.ID),
CodeGenerator.humpToLine(CommonField.REMARK),
"create_time",
"update_time"

};

static String basePackage = "com.stark37125.core";

static String parentPackage = basePackage + ".modules.business";

static String url = "jdbc:postgresql://localhost:5432/password-evaluation";

static String username = "postgres";

static String password = "postgresql";

public static void main(String[] args) {
String[] tableName = {"app_case_evaluation_template_item"};
String moduleName = "evaluation";

generator(tableName, moduleName);

}

private static void generator(String[] tableName, String moduleName) {
String projectPath = System.getProperty("user.dir");
FastAutoGenerator aPublic = FastAutoGenerator.create(new DataSourceConfig.Builder(url, username, password).schema("public"));
aPublic.globalConfig(builder -> {
builder.author(getCurrentName())
.enableSwagger()
// .fileOverride()
.outputDir(projectPath + "/src/main/java/")
.dateType(DateType.ONLY_DATE)
.disableOpenDir()
;

});
aPublic.packageConfig(builder -> {
builder.parent(parentPackage) // 设置父包名
.moduleName(moduleName) // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "/src/main/resources/" + "/mapper/" + moduleName)) // 设置mapperXml生成路径
.mapper("dao")
;
});
aPublic.strategyConfig(builder -> {
builder.addInclude(tableName)
.addTablePrefix("t_", "app_", "sys_")
.entityBuilder().superClass(MyEntity.class)
.enableLombok()
.addIgnoreColumns(commonField)
.controllerBuilder().enableRestStyle().superClass(MyController.class)
.serviceBuilder().superServiceClass(MyService.class)
.superServiceImplClass(MyServiceImpl.class)
.mapperBuilder().superClass(MyMapper.class)
;
});
aPublic.templateConfig(builder -> {
builder.controller("/template/controller.java.vm")
.build();
});
aPublic.injectionConfig(builder -> {
Map<String, String> stringStringMap = new HashMap<>();
stringStringMap.put("vo.java", "/template/vo.java.vm");
stringStringMap.put("param.java", "/template/param.java.vm");
builder.customFile(stringStringMap);
});

aPublic.templateEngine(new CodeVelocityTemplateEngine());
aPublic.execute();
}


private static String getCurrentName() {
try {
Process pop = Runtime.getRuntime().exec("git config user.name");
InputStream inputStream = pop.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
String line;
if ((line = br.readLine()) != null) {
return line;
}
} catch (IOException e) {
e.printStackTrace();
}

return "";
}

}
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
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.Map;

/**
* @author shuzhuo
* @date 2022/5/18 12:16
*/
public class CodeVelocityTemplateEngine extends VelocityTemplateEngine {

private static final String VO_KEY = "vo.java";

private static final String PARAM_KEY = "param.java";

@Override
protected void outputCustomFile(@NotNull Map<String, String> customFile, @NotNull TableInfo tableInfo, @NotNull Map<String, Object> objectMap) {
if (!customFile.containsKey(VO_KEY) && !customFile.containsKey(VO_KEY)) {
super.outputCustomFile(customFile, tableInfo, objectMap);
return;
}
String entityName = tableInfo.getEntityName();
String otherPath = getPathInfo(OutputFile.other);
if (StringUtils.isBlank(otherPath)) {
return;
}
String parent = ((Map<String, String>) objectMap.get("package")).get("Parent");
String packageVo = parent + ".vo";
objectMap.put("packageVo", packageVo);

String packageParam = parent + ".param";
objectMap.put("packageParam", packageParam);

final String finalOtherPath = org.apache.commons.lang3.StringUtils.substringBeforeLast(new File(otherPath).getAbsolutePath(), "\\") + File.separator;
customFile.forEach((key, value) -> {
if (StringUtils.equals(key, VO_KEY)) {
String result = finalOtherPath + "vo";
String fileName = String.format((result + File.separator + entityName + "%s"), "Vo.java");
outputFile(new File(fileName), objectMap, value);
}
if (StringUtils.equals(key, PARAM_KEY)) {
String result = finalOtherPath + "param";
String fileName = String.format((result + File.separator + entityName + "%s"), "Param.java");
outputFile(new File(fileName), objectMap, value);
}

});
}

}
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
package ${package.Controller};

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stark37125.core.responses.ApiResponses;
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.ApiOperation;
import com.stark37125.core.base.model.dto.ErrorCode;
import com.stark37125.core.common.ApiAssert;
import org.springframework.beans.factory.annotation.Autowired;
import com.base.core.framework.converter.BeanConverter;

#if(${restControllerStyle})
import org.springframework.web.bind.annotation.*;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import ${package.Entity}.${entity};
import ${packageVo}.${entity}Vo;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

import java.util.List;

/**
* <p>
* $!{table.comment} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@Validated
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end

@Autowired
private ${table.serviceName} ${table.entityPath}Service;

@GetMapping("/list")
@ApiOperation(value = "获取列表")
public ApiResponses<IPage<${entity}Vo>> list() {
IPage<${entity}Vo> page = ${table.entityPath}Service.page(this.getPage()).convert(e -> e.convert(${entity}Vo.class));
return success(page);
}

@GetMapping("/getById")
@ApiOperation(value = "根据id获取详情")
public ApiResponses<${entity}Vo> getById(@NotBlank String id) {
${entity} entity = ${table.entityPath}Service.getById(id);
ApiAssert.notNull(ErrorCode.builder().msg("该id找不到对应数据").build(),entity);
${entity}Vo vo = entity.convert(${entity}Vo.class);
return success(vo);
}

@PostMapping("/add")
@ApiOperation(value = "新增信息")
public ApiResponses<Void> add(${entity}Param param) {
${entity} entity = BeanConverter.convert(${entity}.class, param);
if (!${table.entityPath}Service.updateById(entity)) {
return failed();
}
return success();
}

@PostMapping("/update")
@ApiOperation(value = "修改信息")
public ApiResponses<Void> update(${entity}Param param) {
${entity} entity = BeanConverter.convert(${entity}.class, param);
if (!${table.entityPath}Service.updateById(entity)) {
return failed();
}
return success();
}

@PostMapping("/del")
@ApiOperation(value = "删除信息")
public ApiResponses<Void> del(@NotEmpty @RequestBody List<String> ids) {
if (!${table.entityPath}Service.removeByIds(ids)) {
return failed();
}
return success();
}
}

#end

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
package ${packageParam};

import java.io.Serializable;
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end

/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Getter
@Setter
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${swagger})
@ApiModel(value = "${entity}Param对象", description = "$!{table.comment}")
#end
#if(${entitySerialVersionUID})
public class ${entity}Param implements Serializable {
#else
public class ${entity}Param {
#end
#if(${entitySerialVersionUID})

private static final long serialVersionUID = 1L;

#end
private String id;
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})

#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
#if(${swagger})
@ApiModelProperty("${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${field.versionField})
@Version
#end
## 逻辑删除注解
#if(${field.logicDeleteField})
@TableLogic
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------


#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}

#if(${chainModel})
public ${entity}Param set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
@Override
public Serializable pkVal() {
#if(${keyPropertyName})
return this.${keyPropertyName};
#else
return null;
#end
}

#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}Param{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}

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
package ${packageVo};

import java.io.Serializable;
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Getter;
import lombok.Setter;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end

/**
* <p>
* $!{table.comment}
* </p>
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Getter
@Setter
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${swagger})
@ApiModel(value = "${entity}Vo对象", description = "$!{table.comment}")
#end
#if(${entitySerialVersionUID})
public class ${entity}Vo implements Serializable {
#else
public class ${entity}Vo {
#end
#if(${entitySerialVersionUID})

private static final long serialVersionUID = 1L;

#end
private String id;
## ---------- BEGIN 字段循环遍历 ----------
#foreach($field in ${table.fields})

#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
#if(${swagger})
@ApiModelProperty("${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${field.versionField})
@Version
#end
## 逻辑删除注解
#if(${field.logicDeleteField})
@TableLogic
#end
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------


#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}

#if(${chainModel})
public ${entity}Vo set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
this.${field.propertyName} = ${field.propertyName};
#if(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
@Override
public Serializable pkVal() {
#if(${keyPropertyName})
return this.${keyPropertyName};
#else
return null;
#end
}

#end
#if(!${entityLombokModel})
@Override
public String toString() {
return "${entity}Vo{" +
#foreach($field in ${table.fields})
#if($!{foreach.index}==0)
"${field.propertyName}=" + ${field.propertyName} +
#else
", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
"}";
}
#end
}