Introducing new features. closed #I42RUU 【新需求】代码生成支持原生element 代码作为avue 的补充

This commit is contained in:
lbw 2021-07-31 16:01:32 +08:00
parent fefdc8db32
commit 1aa9e1d4b0
6 changed files with 333 additions and 59 deletions

View File

@ -24,7 +24,7 @@ import com.pig4cloud.pig.codegen.entity.GenFormConf;
import com.pig4cloud.pig.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pig.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pig.codegen.service.GenFormConfService;
import com.pig4cloud.pig.codegen.util.CodeGenUtils;
import com.pig4cloud.pig.codegen.support.CodeGenKits;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
@ -80,14 +80,13 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setComments(column.get("columnComment"));
columnEntity
.setLowerAttrName(StringUtils.uncapitalize(CodeGenUtils.columnToJava(column.get("columnName"))));
columnEntity.setLowerAttrName(StringUtils.uncapitalize(CodeGenKits.columnToJava(column.get("columnName"))));
columnList.add(columnEntity);
}
context.put("columns", columnList);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), CodeGenUtils.CRUD_PREFIX));
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), CodeGenKits.CRUD_PREFIX));
}
}

View File

@ -29,7 +29,7 @@ import com.pig4cloud.pig.codegen.entity.GenFormConf;
import com.pig4cloud.pig.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pig.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pig.codegen.service.GeneratorService;
import com.pig4cloud.pig.codegen.util.CodeGenUtils;
import com.pig4cloud.pig.codegen.support.CodeGenKits;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@ -83,10 +83,10 @@ public class GeneratorServiceImpl implements GeneratorService {
List<Map<String, String>> columns = generatorMapper.queryColumns(tableName, genConfig.getDsName());
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
return CodeGenUtils.generatorCode(genConfig, table, columns, null, formConfList.get(0));
return CodeGenKits.generatorCode(genConfig, table, columns, null, formConfList.get(0));
}
else {
return CodeGenUtils.generatorCode(genConfig, table, columns, null, null);
return CodeGenKits.generatorCode(genConfig, table, columns, null, null);
}
}
@ -115,10 +115,10 @@ public class GeneratorServiceImpl implements GeneratorService {
List<Map<String, String>> columns = generatorMapper.queryColumns(tableName, genConfig.getDsName());
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
CodeGenUtils.generatorCode(genConfig, table, columns, zip, formConfList.get(0));
CodeGenKits.generatorCode(genConfig, table, columns, zip, formConfList.get(0));
}
else {
CodeGenUtils.generatorCode(genConfig, table, columns, zip, null);
CodeGenKits.generatorCode(genConfig, table, columns, zip, null);
}
}
IoUtil.close(zip);

View File

@ -14,20 +14,7 @@
* limitations under the License.
*/
package com.pig4cloud.pig.codegen.util;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
package com.pig4cloud.pig.codegen.support;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
@ -51,6 +38,14 @@ import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器 工具类 copy
* elunez/eladmin/blob/master/eladmin-generator/src/main/java/me/zhengjie/utils/GenUtil.java
@ -61,7 +56,7 @@ import org.apache.velocity.app.Velocity;
*/
@Slf4j
@UtilityClass
public class CodeGenUtils {
public class CodeGenKits {
public final String CRUD_PREFIX = "export const tableOption =";
@ -81,15 +76,21 @@ public class CodeGenUtils {
private final String AVUE_INDEX_VUE_VM = "avue/index.vue.vm";
private final String ELE_INDEX_VUE_VM = "element/index.vue.vm";
private final String ELE_ADD_UPDATE_VUE_VM = "element/form.vue.vm";
private final String AVUE_API_JS_VM = "avue/api.js.vm";
private final String AVUE_CRUD_JS_VM = "avue/crud.js.vm";
/**
* 配置
*
* @param config
* @return
*/
private List<String> getTemplates() {
private List<String> getTemplates(GenConfig config) {
List<String> templates = new ArrayList<>();
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
@ -99,13 +100,22 @@ public class CodeGenUtils {
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
templates.add("template/avue/api.js.vm");
if (StyleTypeEnum.AVUE.getStyle().equals(config.getStyle())) {
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
} else {
templates.add("template/element/index.vue.vm");
templates.add("template/element/form.vue.vm");
}
return templates;
}
/**
* 生成代码
*
* @return
*/
@SneakyThrows
public Map<String, String> generatorCode(GenConfig genConfig, Map<String, String> table,
@ -119,16 +129,14 @@ public class CodeGenUtils {
if (StrUtil.isNotBlank(genConfig.getComments())) {
tableEntity.setComments(genConfig.getComments());
}
else {
} else {
tableEntity.setComments(table.get("tableComment"));
}
String tablePrefix;
if (StrUtil.isNotBlank(genConfig.getTablePrefix())) {
tablePrefix = genConfig.getTablePrefix();
}
else {
} else {
tablePrefix = config.getString("tablePrefix");
}
@ -136,25 +144,39 @@ public class CodeGenUtils {
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
// 获取需要在swagger文档中隐藏的属性字段
List<Object> hiddenColumns = config.getList("hiddenColumn");
// 列信息
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setColumnName(column.get("columnName"));
columnEntity.setDataType(column.get("dataType"));
columnEntity.setComments(column.get("columnComment"));
columnEntity.setExtra(column.get("extra"));
columnEntity.setNullable("NO".equals(column.get("isNullable")));
columnEntity.setColumnType(column.get("columnType"));
// 隐藏不需要的在接口文档中展示的字段
if (hiddenColumns.contains(column.get("columnName"))) {
columnEntity.setHidden(Boolean.TRUE);
} else {
columnEntity.setHidden(Boolean.FALSE);
}
// 列名转换成Java属性名
String attrName = columnToJava(columnEntity.getColumnName());
columnEntity.setCaseAttrName(attrName);
columnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.get("comments"))) {
// 注意去除换行符号
columnEntity.setComments(StrUtil.removeAllLineBreaks(column.get("comments")));
} else {
columnEntity.setComments(columnEntity.getLowerAttrName());
}
// 列的数据类型转换成Java类型
String attrType = config.getString(columnEntity.getDataType(), "unknowType");
String dataType = StrUtil.subBefore(columnEntity.getDataType(), "(", false);
String attrType = config.getString(dataType, "unknowType");
columnEntity.setAttrType(attrType);
if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true;
@ -173,10 +195,6 @@ public class CodeGenUtils {
tableEntity.setPk(tableEntity.getColumns().get(0));
}
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
// 封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("tableName", tableEntity.getTableName());
@ -190,30 +208,26 @@ public class CodeGenUtils {
if (StrUtil.isNotBlank(genConfig.getComments())) {
map.put("comments", genConfig.getComments());
}
else {
} else {
map.put("comments", tableEntity.getComments());
}
if (StrUtil.isNotBlank(genConfig.getAuthor())) {
map.put("author", genConfig.getAuthor());
}
else {
} else {
map.put("author", config.getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
}
else {
} else {
map.put("moduleName", config.getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
map.put("package", genConfig.getPackageName());
map.put("mainPath", genConfig.getPackageName());
}
else {
} else {
map.put("package", config.getString("package"));
map.put("mainPath", config.getString("mainPath"));
}
@ -224,6 +238,7 @@ public class CodeGenUtils {
/**
* 渲染数据
*
* @param genConfig 配置信息
* @param zip 为空直接返回Map
* @param formConf 表单信息
@ -241,7 +256,7 @@ public class CodeGenUtils {
VelocityContext context = new VelocityContext(map);
// 获取模板列表
List<String> templates = getTemplates();
List<String> templates = getTemplates(genConfig);
Map<String, String> resultMap = new HashMap<>(8);
for (String template : templates) {
@ -303,11 +318,10 @@ public class CodeGenUtils {
/**
* 获取配置信息
*/
private Configuration getConfig() {
public Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties");
}
catch (ConfigurationException e) {
} catch (ConfigurationException e) {
throw new CheckedException("获取配置文件失败,", e);
}
}
@ -352,7 +366,7 @@ public class CodeGenUtils {
return className.toLowerCase() + "_menu.sql";
}
if (template.contains(AVUE_INDEX_VUE_VM)) {
if (template.contains(AVUE_INDEX_VUE_VM) || template.contains(ELE_INDEX_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
@ -368,6 +382,12 @@ public class CodeGenUtils {
+ File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
if (template.contains(ELE_ADD_UPDATE_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ className.toLowerCase() + "-form.vue";
}
return null;
}

View File

@ -0,0 +1,36 @@
package com.pig4cloud.pig.codegen.support;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author lengleng
* @date 2021/7/31
* <p>
* 代码生成风格
*/
@Getter
@AllArgsConstructor
public enum StyleTypeEnum {
/**
* 前端类型-avue 风格
*/
AVUE("0", "avue 风格"),
/**
* 前端类型-element 风格
*/
ELEMENT("1", "element 风格");
/**
* 类型
*/
private String style;
/**
* 描述
*/
private String description;
}

View File

@ -0,0 +1,93 @@
<template>
<el-dialog
:title="!dataForm.id ? '新增' : '修改'"
:close-on-click-modal="false"
:visible.sync="visible">
<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
<el-form-item label="${column.comments}" prop="${column.lowerAttrName}">
<el-input v-model="dataForm.${column.lowerAttrName}" placeholder="${column.comments}"></el-input>
</el-form-item>
#end
#end
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="visible = false">取消</el-button>
<el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit">确定</el-button>
</span>
</el-dialog>
</template>
<script>
import {getObj, addObj, putObj} from '@/api/${pathName}'
export default {
data () {
return {
visible: false,
canSubmit: false,
dataForm: {
#foreach($column in $columns)
#if($column.columnName == $pk.columnName)
${column.lowerAttrName}: 0,
#else
${column.lowerAttrName}: ''#if($velocityCount != $columns.size()),#end
#end
#end
},
dataRule: {
#foreach($column in $columns)
#if($column.columnName != $pk.columnName)
${column.lowerAttrName}: [
{ required: true, message: '${column.comments}不能为空', trigger: 'blur' }
]#if($velocityCount != $columns.size()),#end
#end
#end
}
}
},
methods: {
init (id) {
this.dataForm.${pk.lowerAttrName} = id || 0;
this.visible = true;
this.canSubmit = true;
this.$nextTick(() => {
this.$refs['dataForm'].resetFields()
if (this.dataForm.${pk.lowerAttrName}) {
getObj(this.dataForm.${pk.lowerAttrName}).then(response => {
this.dataForm = response.data.data
})
}
})
},
// 表单提交
dataFormSubmit () {
#[[this.$refs['dataForm'].validate((valid) => {]]#
if (valid) {
this.canSubmit = false;
if (this.dataForm.${pk.lowerAttrName}) {
putObj(this.dataForm).then(data => {
this.$notify.success('修改成功')
this.visible = false
this.$emit('refreshDataList')
}).catch(() => {
this.canSubmit = true;
});
} else {
addObj(this.dataForm).then(data => {
this.$notify.success('添加成功')
this.visible = false
this.$emit('refreshDataList')
}).catch(() => {
this.canSubmit = true;
});
}
}
})
}
}
}
</script>

View File

@ -0,0 +1,126 @@
<template>
<div class="mod-config">
<basic-container>
<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<el-form-item>
<el-button v-if="permissions.${moduleName}_${pathName}_add" icon="el-icon-plus" type="primary" @click="addOrUpdateHandle()">新增</el-button>
</el-form-item>
</el-form>
<div class="avue-crud">
<el-table
:data="dataList"
border
v-loading="dataListLoading">
#foreach($column in $columns)
<el-table-column
prop="${column.lowerAttrName}"
header-align="center"
align="center"
label="${column.comments}">
</el-table-column>
#end
<el-table-column
header-align="center"
align="center"
label="操作">
<template slot-scope="scope">
<el-button v-if="permissions.${moduleName}_${pathName}_edit" type="text" size="small" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.${pk.lowerAttrName})">修改</el-button>
<el-button v-if="permissions.${moduleName}_${pathName}_del" type="text" size="small" icon="el-icon-delete" @click="deleteHandle(scope.row.${pk.lowerAttrName})">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
<div class="avue-crud__pagination">
<el-pagination
@size-change="sizeChangeHandle"
@current-change="currentChangeHandle"
:current-page="pageIndex"
:page-sizes="[10, 20, 50, 100]"
:page-size="pageSize"
:total="totalPage"
background
layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
</div>
<!-- 弹窗, 新增 / 修改 -->
<table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
</basic-container>
</div>
</template>
<script>
import {fetchList, delObj} from '@/api/${pathName}'
import TableForm from './${pathName}-form'
import {mapGetters} from 'vuex'
export default {
data () {
return {
dataForm: {
key: ''
},
dataList: [],
pageIndex: 1,
pageSize: 10,
totalPage: 0,
dataListLoading: false,
addOrUpdateVisible: false
}
},
components: {
TableForm
},
created () {
this.getDataList()
},
computed: {
...mapGetters(['permissions'])
},
methods: {
// 获取数据列表
getDataList () {
this.dataListLoading = true
fetchList(Object.assign({
current: this.pageIndex,
size: this.pageSize
})).then(response => {
this.dataList = response.data.data.records
this.totalPage = response.data.data.total
})
this.dataListLoading = false
},
// 每页数
sizeChangeHandle (val) {
this.pageSize = val
this.pageIndex = 1
this.getDataList()
},
// 当前页
currentChangeHandle (val) {
this.pageIndex = val
this.getDataList()
},
// 新增 / 修改
addOrUpdateHandle (id) {
this.addOrUpdateVisible = true
#[[this.$nextTick(() => {]]#
this.$refs.addOrUpdate.init(id)
})
},
// 删除
deleteHandle (id) {
this.$confirm('是否确认删除ID为' + id, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function () {
return delObj(id)
}).then(data => {
this.$message.success('删除成功')
this.getDataList()
})
}
}
}
</script>