From 921732ab683ed459cc37e7f13f7b0bc77ac04c39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=86=B7=E5=86=B7?= <2270033969@qq.com> Date: Mon, 15 Jul 2024 23:16:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90):=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81anyline=20=E5=8A=A8=E6=80=81=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E8=A1=A8=E5=85=83=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 1. 支持代码生成模板 从 github获取 - 2. 重构代码生成的默认值从配置类获取 --- db/pig.sql | 37 +- pig-visual/pig-codegen/pom.xml | 90 +++-- .../pig/codegen/PigCodeGenApplication.java | 2 + .../config/PigCodeGenDefaultProperties.java | 75 ++++ .../controller/GenDsConfController.java | 10 +- .../controller/GenGroupController.java | 179 ++++---- .../controller/GenTableController.java | 134 +++--- .../controller/GenTemplateController.java | 206 ++++++---- .../controller/GeneratorController.java | 94 ++--- .../pig/codegen/entity/GenTable.java | 21 + .../pig/codegen/entity/GenTemplateEntity.java | 116 +++--- .../pig/codegen/mapper/GenGroupMapper.java | 4 +- .../pig/codegen/mapper/GeneratorMapper.java | 97 ----- .../codegen/mapper/GeneratorMysqlMapper.java | 31 -- .../pig/codegen/service/GenGroupService.java | 10 +- .../service/GenTableColumnService.java | 10 - .../pig/codegen/service/GenTableService.java | 75 ++-- .../codegen/service/GenTemplateService.java | 15 + .../impl/GenDatasourceConfServiceImpl.java | 211 +++++----- .../service/impl/GenGroupServiceImpl.java | 6 +- .../impl/GenTableColumnServiceImpl.java | 1 + .../service/impl/GenTableServiceImpl.java | 316 +++++++++------ .../service/impl/GenTemplateServiceImpl.java | 165 +++++++- .../service/impl/GeneratorServiceImpl.java | 381 ++++++++++-------- .../pig/codegen/util/AutoFillEnum.java | 12 + .../codegen/util/CommonColumnFiledEnum.java | 16 +- .../pig4cloud/pig/codegen/util/GenKit.java | 42 -- .../pig/codegen/util/GeneratorStyleEnum.java | 29 ++ .../pig/codegen/util/GeneratorTypeEnum.java | 21 - .../pig/codegen/util/VFormConfigConsts.java | 25 ++ .../pig/codegen/util/VFormTypeEnum.java | 22 + .../pig/codegen/util/vo/GenCreateTableVO.java | 95 +++++ .../codegen/util/vo/GenTemplateFileVO.java | 37 ++ .../util/vo/{GroupVo.java => GroupVO.java} | 2 +- .../main/resources/mapper/GenGroupMapper.xml | 4 +- .../main/resources/mapper/GenTableMapper.xml | 5 +- .../resources/mapper/GeneratorMySqlMapper.xml | 48 --- .../src/main/resources/template/config.json | 12 - 38 files changed, 1504 insertions(+), 1152 deletions(-) create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java delete mode 100755 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMapper.java delete mode 100755 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMysqlMapper.java create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/AutoFillEnum.java create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorStyleEnum.java delete mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorTypeEnum.java create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormConfigConsts.java create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormTypeEnum.java create mode 100755 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenCreateTableVO.java create mode 100644 pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java rename pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/{GroupVo.java => GroupVO.java} (97%) delete mode 100755 pig-visual/pig-codegen/src/main/resources/mapper/GeneratorMySqlMapper.xml delete mode 100644 pig-visual/pig-codegen/src/main/resources/template/config.json diff --git a/db/pig.sql b/db/pig.sql index 28edcf69..96d424fc 100644 --- a/db/pig.sql +++ b/db/pig.sql @@ -1014,7 +1014,7 @@ CREATE TABLE `gen_table` ( `package_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '项目包名', `version` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '项目版本号', `i18n` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '0' COMMENT '是否生成带有i18n 0 不带有 1带有', - `style` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '0' COMMENT '代码风格', + `style` bigint DEFAULT NULL COMMENT '代码风格', `child_table_name` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '子表名称', `main_field` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '主表关联键', `child_field` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '子表关联键', @@ -1092,23 +1092,6 @@ CREATE TABLE `gen_template` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='模板'; --- ---------------------------- --- Records of gen_template --- ---------------------------- -BEGIN; -INSERT INTO `gen_template` VALUES (1, 'Controller', '${backendPath}/src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java', '后台Controller', 'package ${package}.${moduleName}.controller;\n\n#if($queryList)\nimport cn.hutool.core.util.StrUtil;\n#end\nimport cn.hutool.core.util.ArrayUtil;\nimport cn.hutool.core.collection.CollUtil;\nimport com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;\nimport com.baomidou.mybatisplus.core.toolkit.Wrappers;\nimport com.baomidou.mybatisplus.extension.plugins.pagination.Page;\nimport com.pig4cloud.pig.common.core.util.R;\nimport com.pig4cloud.pig.common.log.annotation.SysLog;\nimport ${package}.${moduleName}.entity.${ClassName}Entity;\nimport ${package}.${moduleName}.service.${ClassName}Service;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport com.pig4cloud.plugin.excel.annotation.ResponseExcel;\nimport io.swagger.v3.oas.annotations.security.SecurityRequirement;\nimport org.springdoc.core.annotations.ParameterObject;\nimport org.springframework.http.HttpHeaders;\nimport io.swagger.v3.oas.annotations.tags.Tag;\nimport io.swagger.v3.oas.annotations.Operation;\nimport lombok.RequiredArgsConstructor;\nimport org.springframework.web.bind.annotation.*;\n\nimport java.util.List;\nimport java.util.Objects;\n\n/**\n * ${tableComment}\n *\n * @author ${author}\n * @date ${datetime}\n */\n@RestController\n@RequiredArgsConstructor\n@RequestMapping(\"/${functionName}\" )\n@Tag(description = \"${functionName}\" , name = \"${tableComment}管理\" )\n@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)\npublic class ${ClassName}Controller {\n\n private final ${ClassName}Service ${className}Service;\n\n /**\n * 分页查询\n * @param page 分页对象\n * @param ${className} ${tableComment}\n * @return\n */\n @Operation(summary = \"分页查询\" , description = \"分页查询\" )\n @GetMapping(\"/page\" )\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_view\')\" )\n public R get${ClassName}Page(@ParameterObject Page page, @ParameterObject ${ClassName}Entity ${className}) {\n LambdaQueryWrapper<${ClassName}Entity> wrapper = Wrappers.lambdaQuery();\n#foreach ($field in $queryList)\n#set($getAttrName=$str.getProperty($field.attrName))\n#set($var=\"${className}.$getAttrName()\")\n#if($field.attrType == \'String\')\n#set($expression=\"StrUtil.isNotBlank\")\n#else\n#set($expression=\"Objects.nonNull\")\n#end\n#if($field.queryType == \'=\')\n wrapper.eq($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'like\' )\n wrapper.like($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'!-\' )\n wrapper.ne($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'>\' )\n wrapper.gt($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'<\' )\n wrapper.lt($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'>=\' )\n wrapper.ge($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'<=\' )\n wrapper.le($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'left like\' )\n wrapper.likeLeft($expression($var),${ClassName}Entity::$getAttrName,$var);\n#elseif( $field.queryType == \'right like\' )\n wrapper.likeRight($expression($var),${ClassName}Entity::$getAttrName,$var);\n#end\n#end\n return R.ok(${className}Service.page(page, wrapper));\n }\n\n\n /**\n * 通过id查询${tableComment}\n * @param ${pk.attrName} id\n * @return R\n */\n @Operation(summary = \"通过id查询\" , description = \"通过id查询\" )\n @GetMapping(\"/{${pk.attrName}}\" )\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_view\')\" )\n public R getById(@PathVariable(\"${pk.attrName}\" ) ${pk.attrType} ${pk.attrName}) {\n return R.ok(${className}Service.getById(${pk.attrName}));\n }\n\n /**\n * 新增${tableComment}\n * @param ${className} ${tableComment}\n * @return R\n */\n @Operation(summary = \"新增${tableComment}\" , description = \"新增${tableComment}\" )\n @SysLog(\"新增${tableComment}\" )\n @PostMapping\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_add\')\" )\n public R save(@RequestBody ${ClassName}Entity ${className}) {\n return R.ok(${className}Service.save(${className}));\n }\n\n /**\n * 修改${tableComment}\n * @param ${className} ${tableComment}\n * @return R\n */\n @Operation(summary = \"修改${tableComment}\" , description = \"修改${tableComment}\" )\n @SysLog(\"修改${tableComment}\" )\n @PutMapping\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_edit\')\" )\n public R updateById(@RequestBody ${ClassName}Entity ${className}) {\n return R.ok(${className}Service.updateById(${className}));\n }\n\n /**\n * 通过id删除${tableComment}\n * @param ids ${pk.attrName}列表\n * @return R\n */\n @Operation(summary = \"通过id删除${tableComment}\" , description = \"通过id删除${tableComment}\" )\n @SysLog(\"通过id删除${tableComment}\" )\n @DeleteMapping\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_del\')\" )\n public R removeById(@RequestBody ${pk.attrType}[] ids) {\n return R.ok(${className}Service.removeBatchByIds(CollUtil.toList(ids)));\n }\n\n\n /**\n * 导出excel 表格\n * @param ${className} 查询条件\n * @param ids 导出指定ID\n * @return excel 文件流\n */\n @ResponseExcel\n @GetMapping(\"/export\")\n @PreAuthorize(\"@pms.hasPermission(\'${moduleName}_${functionName}_export\')\" )\n public List<${ClassName}Entity> export(${ClassName}Entity ${className},${pk.attrType}[] ids) {\n return ${className}Service.list(Wrappers.lambdaQuery(${className}).in(ArrayUtil.isNotEmpty(ids), ${ClassName}Entity::$str.getProperty($pk.attrName), ids));\n }\n}', '2023-02-23 01:16:17', '2023-08-28 22:48:06', '0', '', 'admin'); -INSERT INTO `gen_template` VALUES (2, 'Service', '${backendPath}/src/main/java/${packagePath}/${moduleName}/service/${ClassName}Service.java', 'Service', 'package ${package}.${moduleName}.service;\n\n#if($ChildClassName)\nimport com.github.yulichang.extension.mapping.base.MPJDeepService;\nimport ${package}.${moduleName}.entity.${ChildClassName}Entity;\n#else\nimport com.baomidou.mybatisplus.extension.service.IService;\n#end\nimport ${package}.${moduleName}.entity.${ClassName}Entity;\n\n#if($ChildClassName)\npublic interface ${ClassName}Service extends MPJDeepService<${ClassName}Entity> {\n Boolean saveDeep(${ClassName}Entity ${className});\n\n Boolean updateDeep(${ClassName}Entity ${className});\n\n Boolean removeDeep(Long[] ids);\n\n Boolean removeChild(Long[] ids);\n#else\npublic interface ${ClassName}Service extends IService<${ClassName}Entity> {\n#end\n\n}', '2023-02-23 01:16:53', '2023-06-04 10:35:25', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (3, 'ServiceImpl', '${backendPath}/src/main/java/${packagePath}/${moduleName}/service/impl/${ClassName}ServiceImpl.java', 'ServiceImpl', 'package ${package}.${moduleName}.service.impl;\n\nimport com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;\nimport ${package}.${moduleName}.entity.${ClassName}Entity;\nimport ${package}.${moduleName}.mapper.${ClassName}Mapper;\nimport ${package}.${moduleName}.service.${ClassName}Service;\nimport org.springframework.stereotype.Service;\n#if($ChildClassName)\nimport cn.hutool.core.collection.CollUtil;\nimport com.baomidou.mybatisplus.core.toolkit.Wrappers;\nimport ${package}.${moduleName}.entity.${ChildClassName}Entity;\nimport ${package}.${moduleName}.mapper.${ChildClassName}Mapper;\nimport org.springframework.transaction.annotation.Transactional;\nimport lombok.RequiredArgsConstructor;\nimport java.util.Objects;\n#end\n/**\n * ${tableComment}\n *\n * @author ${author}\n * @date ${datetime}\n */\n@Service\n#if($ChildClassName)\n@RequiredArgsConstructor\n#end\npublic class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper, ${ClassName}Entity> implements ${ClassName}Service {\n#if($ChildClassName)\n private final ${ChildClassName}Mapper ${childClassName}Mapper;\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public Boolean saveDeep(${ClassName}Entity ${className}) {\n baseMapper.insert(${className});\n for (${ChildClassName}Entity ${childClassName} : ${className}.get${ChildClassName}List()) {\n ${childClassName}.$str.setProperty($childField)(${className}.$str.getProperty($mainField)());\n ${childClassName}Mapper.insert( ${childClassName});\n }\n\n return Boolean.TRUE;\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public Boolean updateDeep(${ClassName}Entity ${className}) {\n baseMapper.updateById(${className});\n for (${ChildClassName}Entity ${childClassName} : ${className}.get${ChildClassName}List()) {\n#set($getChildPkName=$str.getProperty(${pk.attrName}))\n if (Objects.isNull(${childClassName}.$getChildPkName())) {\n ${childClassName}.$str.setProperty($childField)(${className}.getId());\n ${childClassName}Mapper.insert(${childClassName});\n } else {\n ${childClassName}Mapper.updateById(${childClassName});\n }\n }\n return Boolean.TRUE;\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public Boolean removeDeep(Long[] ids) {\n baseMapper.deleteBatchIds(CollUtil.toList(ids));\n ${childClassName}Mapper.delete(Wrappers.<${ChildClassName}Entity>lambdaQuery().in(${ChildClassName}Entity::$str.getProperty($childField), ids));\n return Boolean.TRUE;\n }\n\n @Override\n @Transactional(rollbackFor = Exception.class)\n public Boolean removeChild(Long[] ids) {\n ${childClassName}Mapper.deleteBatchIds(CollUtil.toList(ids));\n return Boolean.TRUE;\n }\n#end\n}', '2023-02-23 01:17:36', '2023-08-27 23:29:58', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (4, '实体', '${backendPath}/src/main/java/${packagePath}/${moduleName}/entity/${ClassName}Entity.java', 'Entity', 'package ${package}.${moduleName}.entity;\n\nimport com.baomidou.mybatisplus.annotation.*;\nimport com.baomidou.mybatisplus.extension.activerecord.Model;\nimport io.swagger.v3.oas.annotations.media.Schema;\nimport lombok.Data;\nimport lombok.EqualsAndHashCode;\n#foreach($import in $importList)\nimport $import;\n#end\n#if($ChildClassName)\nimport com.alibaba.excel.annotation.ExcelIgnore;\nimport com.github.yulichang.annotation.EntityMapping;\nimport java.util.List;\n#end\n\n/**\n * ${tableComment}\n *\n * @author ${author}\n * @date ${datetime}\n */\n@Data\n@TableName(\"${tableName}\")\n@EqualsAndHashCode(callSuper = true)\n@Schema(description = \"${tableComment}\")\npublic class ${ClassName}Entity extends Model<${ClassName}Entity> {\n\n#foreach ($field in $fieldList)\n#if(${field.fieldComment})#set($comment=${field.fieldComment})#else #set($comment=${field.attrName})#end\n\n /**\n * $comment\n */\n#if($field.primaryPk == \'1\')\n @TableId(type = IdType.ASSIGN_ID)\n#end\n#if($field.autoFill == \'INSERT\')\n @TableField(fill = FieldFill.INSERT)\n#elseif($field.autoFill == \'INSERT_UPDATE\')\n @TableField(fill = FieldFill.INSERT_UPDATE)\n#elseif($field.autoFill == \'UPDATE\')\n @TableField(fill = FieldFill.UPDATE)\n#end\n#if($field.fieldName == \'del_flag\')\n @TableLogic\n @TableField(fill = FieldFill.INSERT)\n#end\n @Schema(description=\"$comment\"#if($field.hidden),hidden=$field.hidden#end)\n private $field.attrType $field.attrName;\n#end\n#if($ChildClassName)\n @ExcelIgnore\n @TableField(exist = false)\n @EntityMapping(thisField = \"$mainField\", joinField = \"$childField\")\n private List<${ChildClassName}Entity> ${childClassName}List;\n#end\n}', '2023-02-23 01:17:53', '2023-08-27 22:26:06', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (5, 'Mapper', '${backendPath}/src/main/java/${packagePath}/${moduleName}/mapper/${ClassName}Mapper.java', 'Mapper', 'package ${package}.${moduleName}.mapper;\n\nimport com.baomidou.mybatisplus.core.mapper.BaseMapper;\nimport ${package}.${moduleName}.entity.${ClassName}Entity;\nimport org.apache.ibatis.annotations.Mapper;\n\n@Mapper\npublic interface ${ClassName}Mapper extends BaseMapper<${ClassName}Entity> {\n\n\n}', '2023-02-23 01:18:18', '2023-08-28 22:47:02', '0', ' ', 'admin'); -INSERT INTO `gen_template` VALUES (6, 'Mapper.xml', '${backendPath}/src/main/resources/mapper/${ClassName}Mapper.xml', 'Mapper.xml', '\n\n\n\n\n \n#foreach ($field in $fieldList)\n #if($field.primaryPk)\n \n #end\n #if(!$field.primaryPk)\n \n #end\n#end\n \n', '2023-02-23 01:18:35', '2023-06-04 10:34:56', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (7, '权限菜单', '${backendPath}/menu/${functionName}_menu.sql', 'menu.sql', '-- 该脚本不要直接执行, 注意维护菜单的父节点ID 默认 父节点-1 \n#set($menuId=${dateTool.getSystemTime()})\n\n-- 菜单SQL\ninsert into sys_menu ( menu_id,parent_id, path, permission, menu_type, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${menuId}, \'-1\', \'/${moduleName}/${functionName}/index\', \'\', \'0\', \'icon-bangzhushouji\', \'0\', null , \'8\', null , \'${tableComment}管理\');\n\n-- 菜单对应按钮SQL\ninsert into sys_menu ( menu_id,parent_id, permission, menu_type, path, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${math.add($menuId,1)},${menuId}, \'${moduleName}_${functionName}_view\', \'1\', null, \'1\', \'0\', null, \'0\', null, \'${tableComment}查看\');\n\ninsert into sys_menu ( menu_id,parent_id, permission, menu_type, path, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${math.add($menuId,2)},${menuId}, \'${moduleName}_${functionName}_add\', \'1\', null, \'1\', \'0\', null, \'1\', null, \'${tableComment}新增\');\n\ninsert into sys_menu (menu_id, parent_id, permission, menu_type, path, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${math.add($menuId,3)},${menuId}, \'${moduleName}_${functionName}_edit\', \'1\', null, \'1\', \'0\', null, \'2\', null, \'${tableComment}修改\');\n\ninsert into sys_menu (menu_id, parent_id, permission, menu_type, path, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${math.add($menuId,4)},${menuId}, \'${moduleName}_${functionName}_del\', \'1\', null, \'1\', \'0\', null, \'3\', null, \'${tableComment}删除\');\n\ninsert into sys_menu ( menu_id,parent_id, permission, menu_type, path, icon, del_flag, create_time, sort_order, update_time, name)\nvalues (${math.add($menuId,5)},${menuId}, \'${moduleName}_${functionName}_export\', \'1\', null, \'1\', \'0\', null, \'3\', null, \'导入导出\');', '2023-02-23 01:19:08', '2023-08-28 22:06:16', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (8, 'api.ts', '${frontendPath}/src/api/${moduleName}/${functionName}.ts', 'api.ts', 'import request from \"/@/utils/request\"\n\nexport function fetchList(query?: Object) {\n return request({\n url: \'/${moduleName}/${functionName}/page\',\n method: \'get\',\n params: query\n })\n}\n\nexport function addObj(obj?: Object) {\n return request({\n url: \'/${moduleName}/${functionName}\',\n method: \'post\',\n data: obj\n })\n}\n\nexport function getObj(id?: string) {\n return request({\n url: \'/${moduleName}/${functionName}/\' + id,\n method: \'get\'\n })\n}\n\nexport function delObjs(ids?: Object) {\n return request({\n url: \'/${moduleName}/${functionName}\',\n method: \'delete\',\n data: ids\n })\n}\n\nexport function putObj(obj?: Object) {\n return request({\n url: \'/${moduleName}/${functionName}\',\n method: \'put\',\n data: obj\n })\n}\n\n#if($ChildClassName)\nexport function delChildObj(ids?: Object) {\n return request({\n url: \'/${moduleName}/${functionName}/child\',\n method: \'delete\',\n data: ids\n })\n}\n#end', '2023-02-23 01:19:23', '2023-06-04 10:34:17', '0', ' ', ' '); -INSERT INTO `gen_template` VALUES (9, '表格', '${frontendPath}/src/views/${moduleName}/${functionName}/index.vue', '表格不含i18n', '\n\n', '2023-02-23 01:19:35', '2023-08-28 22:53:55', '0', '', 'admin'); -INSERT INTO `gen_template` VALUES (10, '表单', '${frontendPath}/src/views/${moduleName}/${functionName}/form.vue', '表单不含i18n', '\n\n', '2023-02-23 01:19:48', '2023-08-27 22:23:19', '0', '', 'admin'); -INSERT INTO `gen_template` VALUES (11, 'i18n英文模板', '${frontendPath}/src/views/${moduleName}/${functionName}/i18n/en.ts', 'i18n英文模板', 'export default {\n ${functionName}: {\n index: \'#\',\n import${className}Tip: \'import ${ClassName}\',\n#foreach($field in $fieldList)\n ${field.attrName}: \'${field.attrName}\',\n#end\n#foreach($field in $fieldList)\n input$str.pascalCase(${field.attrName})Tip: \'input ${field.attrName}\',\n#end\n }\n}', '2023-02-23 01:20:25', '2023-06-04 10:49:25', '0', '', 'admin'); -INSERT INTO `gen_template` VALUES (12, 'i18n中文模板', '${frontendPath}/src/views/${moduleName}/${functionName}/i18n/zh-cn.ts', 'i18n中文模板', 'export default {\n ${functionName}: {\n index: \'#\',\n import${className}Tip: \'导入${tableComment}\',\n#foreach($field in $fieldList)\n ${field.attrName}: \'#if(${field.fieldComment})${field.fieldComment}#else ${field.attrName}#end\',\n#end\n#foreach($field in $fieldList)\n input$str.pascalCase(${field.attrName})Tip: \'请输入#if(${field.fieldComment})${field.fieldComment}#else ${field.attrName}#end\',\n#end\n }\n}', '2023-02-23 01:20:40', '2023-06-04 10:49:28', '0', '', 'admin'); -COMMIT; -- ---------------------------- -- Table structure for gen_template_group @@ -1120,22 +1103,4 @@ CREATE TABLE `gen_template_group` ( PRIMARY KEY (`group_id`,`template_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='模板分组关联表'; --- ---------------------------- --- Records of gen_template_group --- ---------------------------- -BEGIN; -INSERT INTO `gen_template_group` VALUES (1, 1); -INSERT INTO `gen_template_group` VALUES (1, 2); -INSERT INTO `gen_template_group` VALUES (1, 3); -INSERT INTO `gen_template_group` VALUES (1, 4); -INSERT INTO `gen_template_group` VALUES (1, 5); -INSERT INTO `gen_template_group` VALUES (1, 6); -INSERT INTO `gen_template_group` VALUES (1, 7); -INSERT INTO `gen_template_group` VALUES (1, 8); -INSERT INTO `gen_template_group` VALUES (1, 9); -INSERT INTO `gen_template_group` VALUES (1, 10); -INSERT INTO `gen_template_group` VALUES (1, 11); -INSERT INTO `gen_template_group` VALUES (1, 12); -COMMIT; - SET FOREIGN_KEY_CHECKS = 1; diff --git a/pig-visual/pig-codegen/pom.xml b/pig-visual/pig-codegen/pom.xml index 7b2924e2..e7f84588 100755 --- a/pig-visual/pig-codegen/pom.xml +++ b/pig-visual/pig-codegen/pom.xml @@ -1,20 +1,4 @@ - - 4.0.0 @@ -30,12 +14,13 @@ 代码生成模块 + + 0.0.6 + 8.7.2-jdk17-20240530 + 1.10 + + - - - com.pig4cloud - pig-common-swagger - com.alibaba.cloud @@ -46,16 +31,17 @@ com.alibaba.cloud spring-cloud-starter-alibaba-nacos-config - + com.pig4cloud - pig-common-feign + pig-common-mybatis - + com.pig4cloud pig-common-datasource + com.baomidou mybatis-plus-spring-boot3-starter @@ -64,30 +50,49 @@ com.mysql mysql-connector-j - + - cn.hutool - hutool-json + org.anyline + anyline-environment-spring-data-jdbc + ${anyline.version} + + org.anyline + anyline-data-jdbc-mysql + ${anyline.version} + + com.pig4cloud pig-common-core + + cn.hutool + hutool-json + commons-configuration commons-configuration ${configuration.version} - + com.pig4cloud - pig-common-log + pig-common-swagger + + com.pig4cloud + pig-common-xss + com.pig4cloud pig-common-security + + com.pig4cloud + pig-common-log + org.apache.velocity @@ -101,10 +106,15 @@ - io.springboot.plugin + group.springframework.plugin screw-spring-boot-starter ${screw.version} + + + org.springframework.boot + spring-boot-starter-web + org.springframework.boot @@ -113,13 +123,9 @@ - - boot - cloud - true @@ -127,13 +133,29 @@ org.springframework.boot spring-boot-maven-plugin + + + + repackage + + + CLASSIC + + + io.fabric8 docker-maven-plugin + + false + + + boot + diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java index 9fb7b06e..cf1175f3 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/PigCodeGenApplication.java @@ -20,6 +20,7 @@ package com.pig4cloud.pig.codegen; import com.pig4cloud.pig.common.datasource.annotation.EnableDynamicDataSource; import com.pig4cloud.pig.common.feign.annotation.EnablePigFeignClients; import com.pig4cloud.pig.common.security.annotation.EnablePigResourceServer; +import com.pig4cloud.pig.common.swagger.annotation.EnablePigDoc; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @@ -30,6 +31,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient; */ @EnableDynamicDataSource @EnablePigFeignClients +@EnablePigDoc("gen") @EnableDiscoveryClient @EnablePigResourceServer @SpringBootApplication diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java new file mode 100644 index 00000000..5d0ad260 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/config/PigCodeGenDefaultProperties.java @@ -0,0 +1,75 @@ +package com.pig4cloud.pig.codegen.config; + +import cn.smallbun.screw.core.constant.DefaultConstants; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 代码生成默认配置类 + * + * @author lengleng + * @date 2024/7/15 + */ +@Data +@Configuration(proxyBeanMethods = false) +@ConfigurationProperties(prefix = PigCodeGenDefaultProperties.PREFIX) +public class PigCodeGenDefaultProperties { + + public static final String PREFIX = "codegen"; + + /** + * 是否开启在线更新 + */ + private boolean autoCheckVersion = true; + + /** + * 模板项目地址 + */ + private String onlineUrl = DefaultConstants.CGTM_URL; + + /** + * 生成代码的包名 + */ + private String packageName = "com.pig4cloud.pig"; + + /** + * 生成代码的版本 + */ + private String version = "1.0.0"; + + /** + * 生成代码的模块名 + */ + private String moduleName = "admin"; + + /** + * 生成代码的后端路径 + */ + private String backendPath = "pig"; + + /** + * 生成代码的前端路径 + */ + private String frontendPath = "pig-ui"; + + /** + * 生成代码的作者 + */ + private String author = "pig"; + + /** + * 生成代码的邮箱 + */ + private String email = "sw@pigx.vip"; + + /** + * 表单布局(一列、两列) + */ + private Integer formLayout = 2; + + /** + * 下载方式 (0 文件下载、1写入目录) + */ + private String generatorType = "0"; +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenDsConfController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenDsConfController.java index 2b4d7398..d03f0424 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenDsConfController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenDsConfController.java @@ -18,7 +18,6 @@ package com.pig4cloud.pig.codegen.controller; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.StrUtil; -import cn.hutool.http.ContentType; import cn.smallbun.screw.boot.config.Screw; import cn.smallbun.screw.boot.properties.ScrewProperties; import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; @@ -30,6 +29,7 @@ import com.pig4cloud.pig.codegen.service.GenDatasourceConfService; import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.core.util.SpringContextHolder; import com.pig4cloud.pig.common.security.annotation.Inner; +import com.pig4cloud.pig.common.xss.core.XssCleanIgnore; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @@ -93,6 +93,7 @@ public class GenDsConfController { * @return R */ @PostMapping + @XssCleanIgnore public R save(@RequestBody GenDatasourceConf datasourceConf) { return R.ok(datasourceConfService.saveDsByEnc(datasourceConf)); } @@ -103,6 +104,7 @@ public class GenDsConfController { * @return R */ @PutMapping + @XssCleanIgnore public R updateById(@RequestBody GenDatasourceConf conf) { return R.ok(datasourceConfService.updateDsByEnc(conf)); } @@ -133,11 +135,11 @@ public class GenDsConfController { ScrewProperties screwProperties = SpringContextHolder.getBean(ScrewProperties.class); // 生成 - byte[] data = screw.documentGeneration(dataSource, screwProperties).toByteArray(); + byte[] data = screw.documentGeneration(dsName, dataSource, screwProperties).toByteArray(); response.reset(); response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); - response.setContentType(ContentType.OCTET_STREAM.getValue()); - IoUtil.write(response.getOutputStream(), Boolean.TRUE, data); + response.setContentType("application/octet-stream"); + IoUtil.write(response.getOutputStream(), Boolean.FALSE, data); } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java index 27e235b6..3d0b0599 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenGroupController.java @@ -23,7 +23,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.service.GenGroupService; -import com.pig4cloud.pig.codegen.util.vo.GroupVo; +import com.pig4cloud.pig.codegen.util.vo.GroupVO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.log.annotation.SysLog; @@ -51,95 +51,106 @@ import java.util.List; @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class GenGroupController { - private final GenGroupService genGroupService; + private final GenGroupService genGroupService; - /** - * 分页查询 - * @param page 分页对象 - * @param genGroup 模板分组 - * @return - */ - @Operation(summary = "分页查询", description = "分页查询") - @GetMapping("/page") - @HasPermission("codegen_group_view") - public R getgenGroupPage(Page page, GenGroupEntity genGroup) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() - .like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId()) - .like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName()); - return R.ok(genGroupService.page(page, wrapper)); - } + /** + * 分页查询 + * + * @param page 分页对象 + * @param genGroup 模板分组 + * @return + */ + @Operation(summary = "分页查询", description = "分页查询") + @GetMapping("/page") + @HasPermission("codegen_group_view") + public R getgenGroupPage(Page page, GenGroupEntity genGroup) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() + .like(genGroup.getId() != null, GenGroupEntity::getId, genGroup.getId()) + .like(StrUtil.isNotEmpty(genGroup.getGroupName()), GenGroupEntity::getGroupName, genGroup.getGroupName()); + return R.ok(genGroupService.page(page, wrapper)); + } - /** - * 通过id查询模板分组 - * @param id id - * @return R - */ - @Operation(summary = "通过id查询", description = "通过id查询") - @GetMapping("/{id}") - @HasPermission("codegen_group_view") - public R getById(@PathVariable("id") Long id) { - return R.ok(genGroupService.getGroupVoById(id)); - } + /** + * 通过id查询模板分组 + * + * @param id id + * @return R + */ + @Operation(summary = "通过id查询", description = "通过id查询") + @GetMapping("/{id}") + @HasPermission("codegen_group_view") + public R getById(@PathVariable("id") Long id) { + return R.ok(genGroupService.getGroupVoById(id)); + } - /** - * 新增模板分组 - * @param genTemplateGroup 模板分组 - * @return R - */ - @Operation(summary = "新增模板分组", description = "新增模板分组") - @SysLog("新增模板分组") - @PostMapping - @HasPermission("codegen_group_add") - public R save(@RequestBody TemplateGroupDTO genTemplateGroup) { - genGroupService.saveGenGroup(genTemplateGroup); - return R.ok(); - } + /** + * 新增模板分组 + * + * @param genTemplateGroup 模板分组 + * @return R + */ + @Operation(summary = "新增模板分组", description = "新增模板分组") + @SysLog("新增模板分组") + @PostMapping + @HasPermission("codegen_group_add") + public R save(@RequestBody TemplateGroupDTO genTemplateGroup) { + genGroupService.saveGenGroup(genTemplateGroup); + return R.ok(); + } - /** - * 修改模板分组 - * @param groupVo 模板分组 - * @return R - */ - @Operation(summary = "修改模板分组", description = "修改模板分组") - @SysLog("修改模板分组") - @PutMapping - @HasPermission("codegen_group_edit") - public R updateById(@RequestBody GroupVo groupVo) { - genGroupService.updateGroupAndTemplateById(groupVo); - return R.ok(); - } + /** + * 修改模板分组 + * + * @param groupVo 模板分组 + * @return R + */ + @Operation(summary = "修改模板分组", description = "修改模板分组") + @SysLog("修改模板分组") + @PutMapping + @HasPermission("codegen_group_edit") + public R updateById(@RequestBody GroupVO groupVo) { + genGroupService.updateGroupAndTemplateById(groupVo); + return R.ok(); + } - /** - * 通过id删除模板分组 - * @param ids id列表 - * @return R - */ - @Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组") - @SysLog("通过id删除模板分组") - @DeleteMapping - @HasPermission("codegen_group_del") - public R removeById(@RequestBody Long[] ids) { - genGroupService.delGroupAndTemplate(ids); - return R.ok(); - } + /** + * 通过id删除模板分组 + * + * @param ids id列表 + * @return R + */ + @Operation(summary = "通过id删除模板分组", description = "通过id删除模板分组") + @SysLog("通过id删除模板分组") + @DeleteMapping + @HasPermission("codegen_group_del") + public R removeById(@RequestBody Long[] ids) { + genGroupService.delGroupAndTemplate(ids); + return R.ok(); + } - /** - * 导出excel 表格 - * @param genGroup 查询条件 - * @return excel 文件流 - */ - @ResponseExcel - @GetMapping("/export") - @HasPermission("codegen_group_export") - public List export(GenGroupEntity genGroup) { - return genGroupService.list(Wrappers.query(genGroup)); - } + /** + * 导出excel 表格 + * + * @param genGroup 查询条件 + * @return excel 文件流 + */ + @ResponseExcel + @GetMapping("/export") + @HasPermission("codegen_group_export") + public List export(GenGroupEntity genGroup) { + return genGroupService.list(Wrappers.query(genGroup)); + } - @GetMapping("/list") - @Operation(summary = "查询列表", description = "查询列表") - public R list() { - List list = genGroupService.list(); - return R.ok(list); - } + + /** + * @return 响应信息主体 + */ + @GetMapping("/list") + @Operation(summary = "查询列表", description = "查询列表") + public R list() { + List list = genGroupService.list(Wrappers.lambdaQuery() + .orderByDesc(GenGroupEntity::getCreateTime)); + return R.ok(list); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTableController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTableController.java index 4ee48193..e03449ee 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTableController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTableController.java @@ -61,31 +61,74 @@ public class GenTableController { @Operation(summary = "分页查询", description = "分页查询") @GetMapping("/page") public R getTablePage(Page page, GenTable table) { - - return R.ok(tableService.list(page, table)); + return R.ok(tableService.queryTablePage(page, table)); } /** - * 通过id查询列属性 + * 通过id查询表信息(代码生成设置 + 表 + 字段设置) * @param id id * @return R */ @Operation(summary = "通过id查询", description = "通过id查询") @GetMapping("/{id}") - public R getById(@PathVariable("id") Long id) { + public R getTable(@PathVariable("id") Long id) { return R.ok(tableService.getById(id)); } /** - * 新增列属性 - * @param table 列属性 - * @return R + * 查询数据源所有表 + * @param dsName 数据源 */ - @Operation(summary = "新增列属性", description = "新增列属性") - @SysLog("新增列属性") - @PostMapping - public R save(@RequestBody GenTable table) { - return R.ok(tableService.save(table)); + @GetMapping("/list/{dsName}") + public R listTable(@PathVariable("dsName") String dsName) { + return R.ok(tableService.queryTableList(dsName)); + } + + /** + * 获取表信息 + * @param dsName 数据源 + * @param tableName 表名称 + */ + @GetMapping("/{dsName}/{tableName}") + public R getTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) { + return R.ok(tableService.queryOrBuildTable(dsName, tableName)); + } + + /** + * 查询表DDL语句 + * @param dsName 数据源 + * @param tableName 表名称 + */ + @GetMapping("/column/{dsName}/{tableName}") + public R getColumn(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception { + return R.ok(tableService.queryTableColumn(dsName, tableName)); + } + + /** + * 查询表DDL语句 + * @param dsName 数据源 + * @param tableName 表名称 + */ + @GetMapping("/ddl/{dsName}/{tableName}") + public R getDdl(@PathVariable("dsName") String dsName, @PathVariable String tableName) throws Exception { + return R.ok(tableService.queryTableDdl(dsName, tableName)); + } + + /** + * 同步表信息 + * @param dsName 数据源 + * @param tableName 表名称 + */ + @GetMapping("/sync/{dsName}/{tableName}") + public R syncTable(@PathVariable("dsName") String dsName, @PathVariable String tableName) { + // 表配置删除 + tableService.remove( + Wrappers.lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName)); + // 字段配置删除 + tableColumnService.remove(Wrappers.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, dsName) + .eq(GenTableColumnEntity::getTableName, tableName)); + return R.ok(tableService.queryOrBuildTable(dsName, tableName)); } /** @@ -101,15 +144,16 @@ public class GenTableController { } /** - * 通过id删除列属性 - * @param id id - * @return R + * 修改表字段数据 + * @param dsName 数据源 + * @param tableName 表名称 + * @param tableFieldList 字段列表 */ - @Operation(summary = "通过id删除列属性", description = "通过id删除列属性") - @SysLog("通过id删除列属性") - @DeleteMapping("/{id}") - public R removeById(@PathVariable Long id) { - return R.ok(tableService.removeById(id)); + @PutMapping("/field/{dsName}/{tableName}") + public R updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName, + @RequestBody List tableFieldList) { + tableColumnService.updateTableField(dsName, tableName, tableFieldList); + return R.ok(); } /** @@ -123,54 +167,4 @@ public class GenTableController { return tableService.list(Wrappers.query(table)); } - @GetMapping("/list/{dsName}") - public R listTable(@PathVariable("dsName") String dsName) { - return R.ok(tableService.queryDsAllTable(dsName)); - } - - @GetMapping("/column/{dsName}/{tableName}") - public R column(@PathVariable("dsName") String dsName, @PathVariable String tableName) { - return R.ok(tableService.queryColumn(dsName, tableName)); - } - - /** - * 获取表信息 - * @param dsName 数据源 - * @param tableName 表名称 - */ - @GetMapping("/{dsName}/{tableName}") - public R info(@PathVariable("dsName") String dsName, @PathVariable String tableName) { - return R.ok(tableService.queryOrBuildTable(dsName, tableName)); - } - - /** - * 同步表信息 - * @param dsName 数据源 - * @param tableName 表名称 - */ - @GetMapping("/sync/{dsName}/{tableName}") - public R sync(@PathVariable("dsName") String dsName, @PathVariable String tableName) { - // 表配置删除 - tableService.remove( - Wrappers.lambdaQuery().eq(GenTable::getDsName, dsName).eq(GenTable::getTableName, tableName)); - // 字段配置删除 - tableColumnService.remove(Wrappers.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, dsName) - .eq(GenTableColumnEntity::getTableName, tableName)); - return R.ok(tableService.queryOrBuildTable(dsName, tableName)); - } - - /** - * 修改表字段数据 - * @param dsName 数据源 - * @param tableName 表名称 - * @param tableFieldList 字段列表 - */ - @PutMapping("/field/{dsName}/{tableName}") - public R updateTableField(@PathVariable("dsName") String dsName, @PathVariable String tableName, - @RequestBody List tableFieldList) { - tableColumnService.updateTableField(dsName, tableName, tableFieldList); - return R.ok(); - } - } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java index 8d0e566d..418ba2bb 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GenTemplateController.java @@ -27,6 +27,7 @@ import com.pig4cloud.pig.codegen.service.GenTemplateService; import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.pig.common.log.annotation.SysLog; import com.pig4cloud.pig.common.security.annotation.HasPermission; +import com.pig4cloud.pig.common.xss.core.XssCleanIgnore; import com.pig4cloud.plugin.excel.annotation.ResponseExcel; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; @@ -50,97 +51,132 @@ import java.util.List; @SecurityRequirement(name = HttpHeaders.AUTHORIZATION) public class GenTemplateController { - private final GenTemplateService genTemplateService; + private final GenTemplateService genTemplateService; - /** - * 分页查询 - * @param page 分页对象 - * @param genTemplate 模板 - * @return - */ - @Operation(summary = "分页查询", description = "分页查询") - @GetMapping("/page") - @HasPermission("codegen_template_view") - public R getgenTemplatePage(Page page, GenTemplateEntity genTemplate) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() - .like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId()) - .like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName, - genTemplate.getTemplateName()); - return R.ok(genTemplateService.page(page, wrapper)); - } + /** + * 分页查询 + * + * @param page 分页对象 + * @param genTemplate 模板 + * @return + */ + @Operation(summary = "分页查询", description = "分页查询") + @GetMapping("/page") + @HasPermission("codegen_template_view") + public R getGenTemplatePage(Page page, GenTemplateEntity genTemplate) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery() + .like(genTemplate.getId() != null, GenTemplateEntity::getId, genTemplate.getId()) + .like(StrUtil.isNotEmpty(genTemplate.getTemplateName()), GenTemplateEntity::getTemplateName, + genTemplate.getTemplateName()); + return R.ok(genTemplateService.page(page, wrapper)); + } - /** - * 查询全部模板 - * @return - */ - @Operation(summary = "查询全部", description = "查询全部") - @GetMapping("/list") - @HasPermission("codegen_template_view") - public R list() { - return R.ok(genTemplateService.list(Wrappers.emptyWrapper())); - } + /** + * 查询全部模板 + * + * @return + */ + @Operation(summary = "查询全部", description = "查询全部") + @GetMapping("/list") + @HasPermission("codegen_template_view") + public R list() { + return R.ok(genTemplateService.list(Wrappers.lambdaQuery() + .orderByDesc(GenTemplateEntity::getCreateTime))); + } - /** - * 通过id查询模板 - * @param id id - * @return R - */ - @Operation(summary = "通过id查询", description = "通过id查询") - @GetMapping("/{id}") - @HasPermission("codegen_template_view") - public R getById(@PathVariable("id") Long id) { - return R.ok(genTemplateService.getById(id)); - } + /** + * 通过id查询模板 + * + * @param id id + * @return R + */ + @Operation(summary = "通过id查询", description = "通过id查询") + @GetMapping("/{id}") + @HasPermission("codegen_template_view") + public R getById(@PathVariable("id") Long id) { + return R.ok(genTemplateService.getById(id)); + } - /** - * 新增模板 - * @param genTemplate 模板 - * @return R - */ - @Operation(summary = "新增模板", description = "新增模板") - @SysLog("新增模板") - @PostMapping - @HasPermission("codegen_template_add") - public R save(@RequestBody GenTemplateEntity genTemplate) { - return R.ok(genTemplateService.save(genTemplate)); - } + /** + * 新增模板 + * + * @param genTemplate 模板 + * @return R + */ + @XssCleanIgnore + @Operation(summary = "新增模板", description = "新增模板") + @SysLog("新增模板") + @PostMapping + @HasPermission("codegen_template_add") + public R save(@RequestBody GenTemplateEntity genTemplate) { + return R.ok(genTemplateService.save(genTemplate)); + } - /** - * 修改模板 - * @param genTemplate 模板 - * @return R - */ - @Operation(summary = "修改模板", description = "修改模板") - @SysLog("修改模板") - @PutMapping - @HasPermission("codegen_template_edit") - public R updateById(@RequestBody GenTemplateEntity genTemplate) { - return R.ok(genTemplateService.updateById(genTemplate)); - } + /** + * 修改模板 + * + * @param genTemplate 模板 + * @return R + */ + @XssCleanIgnore + @Operation(summary = "修改模板", description = "修改模板") + @SysLog("修改模板") + @PutMapping + @HasPermission("codegen_template_edit") + public R updateById(@RequestBody GenTemplateEntity genTemplate) { + return R.ok(genTemplateService.updateById(genTemplate)); + } - /** - * 通过id删除模板 - * @param ids id列表 - * @return R - */ - @Operation(summary = "通过id删除模板", description = "通过id删除模板") - @SysLog("通过id删除模板") - @DeleteMapping - @HasPermission("codegen_template_del") - public R removeById(@RequestBody Long[] ids) { - return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids))); - } + /** + * 通过id删除模板 + * + * @param ids id列表 + * @return R + */ + @Operation(summary = "通过id删除模板", description = "通过id删除模板") + @SysLog("通过id删除模板") + @DeleteMapping + @HasPermission("codegen_template_del") + public R removeById(@RequestBody Long[] ids) { + return R.ok(genTemplateService.removeBatchByIds(CollUtil.toList(ids))); + } - /** - * 导出excel 表格 - * @param genTemplate 查询条件 - * @return excel 文件流 - */ - @ResponseExcel - @GetMapping("/export") - @HasPermission("codegen_template_export") - public List export(GenTemplateEntity genTemplate) { - return genTemplateService.list(Wrappers.query(genTemplate)); - } + /** + * 导出excel 表格 + * + * @param genTemplate 查询条件 + * @return excel 文件流 + */ + @ResponseExcel + @GetMapping("/export") + @HasPermission("codegen_template_export") + public List export(GenTemplateEntity genTemplate) { + return genTemplateService.list(Wrappers.query(genTemplate)); + } + + /** + * 在线更新模板 + * + * @return R + */ + @Operation(summary = "在线更新模板", description = "在线更新模板") + @GetMapping("/online") + @HasPermission("codegen_template_view") + public R online() { + return genTemplateService.onlineUpdate(); + } + + + /** + * 检查版本 + * + * @return {@link R } + */ + @Operation(summary = "在线检查模板", description = "在线检查模板") + @GetMapping("/checkVersion") + @HasPermission("codegen_template_view") + public R checkVersion() { + return genTemplateService.checkVersion(); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java index cd1305c6..8b6cd4e8 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/controller/GeneratorController.java @@ -46,59 +46,61 @@ import java.util.zip.ZipOutputStream; @RequestMapping("/generator") public class GeneratorController { - private final GeneratorService generatorService; + private final GeneratorService generatorService; - /** - * ZIP 下载生成代码 - * @param tableIds 数据表ID - * @param response 流输出对象 - */ - @SneakyThrows - @GetMapping("/download") - public void download(String tableIds, HttpServletResponse response) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(outputStream); + /** + * ZIP 下载生成代码 + * + * @param tableIds 数据表ID + * @param response 流输出对象 + */ + @SneakyThrows + @GetMapping("/download") + public void download(String tableIds, HttpServletResponse response) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); - // 生成代码 - for (String tableId : tableIds.split(StrUtil.COMMA)) { - generatorService.downloadCode(Long.parseLong(tableId), zip); - } + // 生成代码 + for (String tableId : tableIds.split(StrUtil.COMMA)) { + generatorService.downloadCode(Long.parseLong(tableId), zip); + } - IoUtil.close(zip); + IoUtil.close(zip); - // zip压缩包数据 - byte[] data = outputStream.toByteArray(); + // zip压缩包数据 + byte[] data = outputStream.toByteArray(); - response.reset(); - response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds)); - response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); - response.setContentType("application/octet-stream; charset=UTF-8"); - IoUtil.write(response.getOutputStream(), false, data); - } + response.reset(); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", tableIds)); + response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length)); + response.setContentType("application/octet-stream; charset=UTF-8"); + IoUtil.write(response.getOutputStream(), false, data); + } - /** - * 目标目录生成代码 - */ - @ResponseBody - @GetMapping("/code") - public R code(String tableIds) throws Exception { - // 生成代码 - for (String tableId : tableIds.split(StrUtil.COMMA)) { - generatorService.generatorCode(Long.valueOf(tableId)); - } + /** + * 目标目录生成代码 + */ + @ResponseBody + @GetMapping("/code") + public R code(String tableIds) throws Exception { + // 生成代码 + for (String tableId : tableIds.split(StrUtil.COMMA)) { + generatorService.generatorCode(Long.valueOf(tableId)); + } - return R.ok(); - } + return R.ok(); + } - /** - * 预览代码 - * @param tableId 表ID - * @return - */ - @SneakyThrows - @GetMapping("/preview") - public List> preview(Long tableId) { - return generatorService.preview(tableId); - } + /** + * 预览代码 + * + * @param tableId 表ID + * @return + */ + @SneakyThrows + @GetMapping("/preview") + public List> preview(Long tableId) { + return generatorService.preview(tableId); + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTable.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTable.java index ca25c3b9..efec0b5e 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTable.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTable.java @@ -157,12 +157,33 @@ public class GenTable extends Model { */ private Long style; + /** + * 子表名称 + */ + private String childTableName; + + /** + * 主表关联键 + */ + private String mainField; + + /** + * 子表关联键 + */ + private String childField; + /** * 字段列表 */ @TableField(exist = false) private List fieldList; + /** + * 子表字段列表 + */ + @TableField(exist = false) + private List childFieldList; + /** * 代码风格(模版分组信息) */ diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java index 10b0f185..de36c967 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/entity/GenTemplateEntity.java @@ -37,73 +37,73 @@ import java.time.LocalDateTime; @Schema(description = "模板") public class GenTemplateEntity extends Model { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * 主键 - */ - @TableId(type = IdType.ASSIGN_ID) - @Schema(description = "主键") - private Long id; + /** + * 主键 + */ + @TableId(type = IdType.ASSIGN_ID) + @Schema(description = "主键") + private Long id; - /** - * 模板名称 - */ - @Schema(description = "模板名称") - private String templateName; + /** + * 模板名称 + */ + @Schema(description = "模板名称") + private String templateName; - /** - * 模板路径 - */ - @Schema(description = "模板路径") - private String generatorPath; + /** + * 模板路径 + */ + @Schema(description = "模板路径") + private String generatorPath; - /** - * 模板描述 - */ - @Schema(description = "模板描述") - private String templateDesc; + /** + * 模板描述 + */ + @Schema(description = "模板描述") + private String templateDesc; - /** - * 模板代码 - */ - @Schema(description = "模板代码") - private String templateCode; + /** + * 模板代码 + */ + @Schema(description = "模板代码") + private String templateCode; - /** - * 创建人 - */ - @TableField(fill = FieldFill.INSERT) - @Schema(description = "创建人") - private String createBy; + /** + * 创建人 + */ + @TableField(fill = FieldFill.INSERT) + @Schema(description = "创建人") + private String createBy; - /** - * 修改人 - */ - @TableField(fill = FieldFill.UPDATE) - @Schema(description = "修改人") - private String updateBy; + /** + * 修改人 + */ + @TableField(fill = FieldFill.UPDATE) + @Schema(description = "修改人") + private String updateBy; - /** - * 创建时间 - */ - @Schema(description = "创建时间") - @TableField(fill = FieldFill.INSERT) - private LocalDateTime createTime; + /** + * 创建时间 + */ + @Schema(description = "创建时间") + @TableField(fill = FieldFill.INSERT) + private LocalDateTime createTime; - /** - * 修改时间 - */ - @Schema(description = "修改时间") - @TableField(fill = FieldFill.UPDATE) - private LocalDateTime updateTime; + /** + * 修改时间 + */ + @Schema(description = "修改时间") + @TableField(fill = FieldFill.UPDATE) + private LocalDateTime updateTime; - /** - * 删除标识(0-正常,1-删除) - */ - @TableLogic - @TableField(fill = FieldFill.INSERT) - @Schema(description = "删除标记,1:已删除,0:正常") - private String delFlag; + /** + * 删除标识(0-正常,1-删除) + */ + @TableLogic + @TableField(fill = FieldFill.INSERT) + @Schema(description = "删除标记,1:已删除,0:正常") + private String delFlag; } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GenGroupMapper.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GenGroupMapper.java index 146e2fa1..b6039317 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GenGroupMapper.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GenGroupMapper.java @@ -19,7 +19,7 @@ package com.pig4cloud.pig.codegen.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.pig4cloud.pig.codegen.entity.GenGroupEntity; -import com.pig4cloud.pig.codegen.util.vo.GroupVo; +import com.pig4cloud.pig.codegen.util.vo.GroupVO; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; @@ -32,6 +32,6 @@ import org.apache.ibatis.annotations.Param; @Mapper public interface GenGroupMapper extends BaseMapper { - GroupVo getGroupVoById(@Param("id") Long id); + GroupVO getGroupVoById(@Param("id") Long id); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMapper.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMapper.java deleted file mode 100755 index 6952289a..00000000 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMapper.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2018-2025, lengleng All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * Neither the name of the pig4cloud.com developer nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * Author: lengleng (wangiegie@gmail.com) - */ - -package com.pig4cloud.pig.codegen.mapper; - -import com.baomidou.dynamic.datasource.annotation.DS; -import com.baomidou.mybatisplus.annotation.InterceptorIgnore; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -import com.pig4cloud.pig.codegen.entity.ColumnEntity; -import org.apache.ibatis.annotations.Param; - -import java.util.List; -import java.util.Map; - -/** - * 代码生成器 - * - * @author lengleng - * @date 2018-07-30 - */ -public interface GeneratorMapper extends BaseMapper { - - /** - * 查询全部的表 - * @return - */ - @InterceptorIgnore(tenantLine = "true") - List> queryTable(); - - /** - * 分页查询表格 - * @param page 分页信息 - * @param tableName 表名称 - * @return - */ - @InterceptorIgnore(tenantLine = "true") - IPage> queryTable(Page page, @Param("tableName") String tableName); - - /** - * 查询表信息 - * @param tableName 表名称 - * @param dsName 数据源名称 - * @return - */ - @DS("#last") - @InterceptorIgnore(tenantLine = "true") - Map queryTable(@Param("tableName") String tableName, String dsName); - - /** - * 分页查询表分页信息 - * @param page - * @param tableName - * @param dsName - * @return - */ - @DS("#last") - @InterceptorIgnore(tenantLine = "true") - IPage selectTableColumn(Page page, @Param("tableName") String tableName, - @Param("dsName") String dsName); - - /** - * 查询表全部列信息 - * @param tableName - * @param dsName - * @return - */ - @DS("#last") - @InterceptorIgnore(tenantLine = "true") - List selectTableColumn(@Param("tableName") String tableName, @Param("dsName") String dsName); - - /** - * 查询表全部列信息 - * @param tableName 表名称 - * @param dsName 数据源名称 - * @return - */ - @DS("#last") - @InterceptorIgnore(tenantLine = "true") - List> selectMapTableColumn(@Param("tableName") String tableName, String dsName); - -} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMysqlMapper.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMysqlMapper.java deleted file mode 100755 index 26a7cb63..00000000 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/mapper/GeneratorMysqlMapper.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2018-2025, lengleng All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * Neither the name of the pig4cloud.com developer nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * Author: lengleng (wangiegie@gmail.com) - */ - -package com.pig4cloud.pig.codegen.mapper; - -import org.apache.ibatis.annotations.Mapper; - -/** - * 支持 mysql 代码生成器 - * - * @author lengleng - * @date 2020-12-11 - */ -@Mapper -public interface GeneratorMysqlMapper extends GeneratorMapper { - -} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenGroupService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenGroupService.java index 555d1405..69fce638 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenGroupService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenGroupService.java @@ -19,7 +19,7 @@ package com.pig4cloud.pig.codegen.service; import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pig.codegen.entity.GenGroupEntity; -import com.pig4cloud.pig.codegen.util.vo.GroupVo; +import com.pig4cloud.pig.codegen.util.vo.GroupVO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; /** @@ -33,7 +33,7 @@ public interface GenGroupService extends IService { void saveGenGroup(TemplateGroupDTO genTemplateGroup); /** - * 删除分组关系 + * 删除分组极其关系 * @param ids */ void delGroupAndTemplate(Long[] ids); @@ -42,12 +42,12 @@ public interface GenGroupService extends IService { * 查询group数据 * @param id */ - GroupVo getGroupVoById(Long id); + GroupVO getGroupVoById(Long id); /** * 更新group数据 - * @param groupVo + * @param GroupVo */ - void updateGroupAndTemplateById(GroupVo groupVo); + void updateGroupAndTemplateById(GroupVO GroupVo); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableColumnService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableColumnService.java index 812ab1ba..2cfa0aac 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableColumnService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableColumnService.java @@ -30,18 +30,8 @@ import java.util.List; */ public interface GenTableColumnService extends IService { - /** - * 初始化字段列表 - * @param tableFieldList 表字段列表 - */ void initFieldList(List tableFieldList); - /** - * 更新表字段 - * @param dsName 数据源名称 - * @param tableName 表名称 - * @param tableFieldList 表字段列表 - */ void updateTableField(String dsName, String tableName, List tableFieldList); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java index 0b41754d..6430bbfa 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTableService.java @@ -21,9 +21,9 @@ import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pig.codegen.entity.GenTable; +import org.anyline.metadata.Table; import java.util.List; -import java.util.Map; /** * 列属性 @@ -33,41 +33,50 @@ import java.util.Map; */ public interface GenTableService extends IService { - /** - * 获取默认配置信息 - * @return 默认配置信息 - */ - Map getGeneratorConfig(); - /** - * 分页查询表格列表 - * @param page 分页对象 - * @param table 查询条件 - * @return 表格列表分页结果 - */ - IPage list(Page page, GenTable table); + /** + * 查询对应数据源的表 + * + * @param page 分页信息 + * @param table 查询条件 + * @return 表 + */ + IPage queryTablePage(Page page, GenTable table); - /** - * 根据数据源名称和表名查询或构建表格 - * @param dsName 数据源名称 - * @param tableName 表名 - * @return 查询到的表格信息 - */ - GenTable queryOrBuildTable(String dsName, String tableName); + /** + * 查询表信息(列),然后插入到中间表中 + * + * @param dsName 数据源 + * @param tableName 表名 + * @return GenTable + */ + GenTable queryOrBuildTable(String dsName, String tableName); - /** - * 查询指定数据源下的所有表格 - * @param dsName 数据源名称 - * @return 所有表格的列表 - */ - List> queryDsAllTable(String dsName); + /** + * 查询表ddl 语句 + * + * @param dsName 数据源名称 + * @param tableName 表名称 + * @return ddl 语句 + * @throws Exception + */ + String queryTableDdl(String dsName, String tableName) throws Exception; - /** - * 查询指定数据源和表名的列信息 - * @param dsName 数据源名称 - * @param tableName 表名 - * @return 列信息列表 - */ - List> queryColumn(String dsName, String tableName); + /** + * 查询数据源里面的全部表 + * + * @param dsName 数据源名称 + * @return table + */ + List queryTableList(String dsName); + + /** + * 查询表的全部字段 + * + * @param dsName 数据源 + * @param tableName 表名称 + * @return column + */ + List queryTableColumn(String dsName, String tableName); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java index a465dc20..644a662d 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/GenTemplateService.java @@ -19,6 +19,7 @@ package com.pig4cloud.pig.codegen.service; import com.baomidou.mybatisplus.extension.service.IService; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; +import com.pig4cloud.pig.common.core.util.R; /** * 模板 @@ -28,4 +29,18 @@ import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; */ public interface GenTemplateService extends IService { + + /** + * 检查版本 + * + * @return {@link R } + */ + R checkVersion(); + + /** + * 在线更新 + * + * @return {@link R } + */ + R onlineUpdate(); } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java index 5b83efb2..2077483c 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenDatasourceConfServiceImpl.java @@ -19,9 +19,8 @@ package com.pig4cloud.pig.codegen.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.creator.DataSourceCreator; import com.baomidou.dynamic.datasource.creator.DataSourceProperty; -import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator; -import com.baomidou.dynamic.datasource.creator.druid.DruidConfig; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.pig4cloud.pig.codegen.entity.GenDatasourceConf; import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper; @@ -49,124 +48,122 @@ import java.sql.SQLException; @Service @RequiredArgsConstructor public class GenDatasourceConfServiceImpl extends ServiceImpl - implements GenDatasourceConfService { + implements GenDatasourceConfService { - private final StringEncryptor stringEncryptor; + private final StringEncryptor stringEncryptor; - private final DefaultDataSourceCreator druidDataSourceCreator; + private final DataSourceCreator hikariDataSourceCreator; - /** - * 保存数据源并且加密 - * @param conf - * @return - */ - @Override - public Boolean saveDsByEnc(GenDatasourceConf conf) { - // 校验配置合法性 - if (!checkDataSource(conf)) { - return Boolean.FALSE; - } + /** + * 保存数据源并且加密 + * + * @param conf + * @return + */ + @Override + public Boolean saveDsByEnc(GenDatasourceConf conf) { + // 校验配置合法性 + if (!checkDataSource(conf)) { + return Boolean.FALSE; + } - // 添加动态数据源 - addDynamicDataSource(conf); + // 添加动态数据源 + addDynamicDataSource(conf); - // 更新数据库配置 - conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); - this.baseMapper.insert(conf); - return Boolean.TRUE; - } + // 更新数据库配置 + conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); + this.baseMapper.insert(conf); + return Boolean.TRUE; + } - /** - * 更新数据源 - * @param conf 数据源信息 - * @return - */ - @Override - public Boolean updateDsByEnc(GenDatasourceConf conf) { - if (!checkDataSource(conf)) { - return Boolean.FALSE; - } - // 先移除 - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName()); + /** + * 更新数据源 + * + * @param conf 数据源信息 + * @return + */ + @Override + public Boolean updateDsByEnc(GenDatasourceConf conf) { + if (!checkDataSource(conf)) { + return Boolean.FALSE; + } + // 先移除 + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + dynamicRoutingDataSource.removeDataSource(baseMapper.selectById(conf.getId()).getName()); - // 再添加 - addDynamicDataSource(conf); + // 再添加 + addDynamicDataSource(conf); - // 更新数据库配置 - if (StrUtil.isNotBlank(conf.getPassword())) { - conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); - } - this.baseMapper.updateById(conf); - return Boolean.TRUE; - } + // 更新数据库配置 + if (StrUtil.isNotBlank(conf.getPassword())) { + conf.setPassword(stringEncryptor.encrypt(conf.getPassword())); + } + this.baseMapper.updateById(conf); + return Boolean.TRUE; + } - /** - * 通过数据源名称删除 - * @param dsIds 数据源ID - * @return - */ - @Override - public Boolean removeByDsId(Long[] dsIds) { - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - this.baseMapper.selectBatchIds(CollUtil.toList(dsIds)) - .forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName())); - this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds)); - return Boolean.TRUE; - } + /** + * 通过数据源名称删除 + * + * @param dsIds 数据源ID + * @return + */ + @Override + public Boolean removeByDsId(Long[] dsIds) { + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + this.baseMapper.selectBatchIds(CollUtil.toList(dsIds)) + .forEach(ds -> dynamicRoutingDataSource.removeDataSource(ds.getName())); + this.baseMapper.deleteBatchIds(CollUtil.toList(dsIds)); + return Boolean.TRUE; + } - /** - * 添加动态数据源 - * @param conf 数据源信息 - */ - @Override - public void addDynamicDataSource(GenDatasourceConf conf) { - DataSourceProperty dataSourceProperty = new DataSourceProperty(); - dataSourceProperty.setPoolName(conf.getName()); - dataSourceProperty.setUrl(conf.getUrl()); - dataSourceProperty.setUsername(conf.getUsername()); - dataSourceProperty.setPassword(conf.getPassword()); + /** + * 添加动态数据源 + * + * @param conf 数据源信息 + */ + @Override + public void addDynamicDataSource(GenDatasourceConf conf) { + DataSourceProperty dataSourceProperty = new DataSourceProperty(); + dataSourceProperty.setPoolName(conf.getName()); + dataSourceProperty.setUrl(conf.getUrl()); + dataSourceProperty.setUsername(conf.getUsername()); + dataSourceProperty.setPassword(conf.getPassword()); + DataSource dataSource = hikariDataSourceCreator.createDataSource(dataSourceProperty); - // 增加 ValidationQuery 参数 - DruidConfig druidConfig = new DruidConfig(); - dataSourceProperty.setDruid(druidConfig); - DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty); + DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); + dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource); + } - DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class); - dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource); - } + /** + * 校验数据源配置是否有效 + * + * @param conf 数据源信息 + * @return 有效/无效 + */ + @Override + public Boolean checkDataSource(GenDatasourceConf conf) { + String url; + // JDBC 配置形式 + if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) { + url = conf.getUrl(); + } else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) { + // 主机形式 sql server 特殊处理 + DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); + url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); + } else { + DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); + url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); + } - /** - * 校验数据源配置是否有效 - * @param conf 数据源信息 - * @return 有效/无效 - */ - @Override - public Boolean checkDataSource(GenDatasourceConf conf) { - String url; - // JDBC 配置形式 - if (DsConfTypeEnum.JDBC.getType().equals(conf.getConfType())) { - url = conf.getUrl(); - } - else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) { - // 主机形式 sql server 特殊处理 - DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); - url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); - } - else { - DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType()); - url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName()); - } + conf.setUrl(url); - conf.setUrl(url); - - try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) { - } - catch (SQLException e) { - log.error("数据源配置 {} , 获取链接失败", conf.getName(), e); - throw new RuntimeException("数据库配置错误,链接失败"); - } - return Boolean.TRUE; - } + try (Connection connection = DriverManager.getConnection(url, conf.getUsername(), conf.getPassword())) { + } catch (SQLException e) { + log.error("数据源配置 {} , 获取链接失败", conf.getName(), e); + throw new RuntimeException("数据库配置错误,链接失败"); + } + return Boolean.TRUE; + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenGroupServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenGroupServiceImpl.java index 6e92bf76..f1fedc5e 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenGroupServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenGroupServiceImpl.java @@ -25,7 +25,7 @@ import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity; import com.pig4cloud.pig.codegen.mapper.GenGroupMapper; import com.pig4cloud.pig.codegen.service.GenGroupService; import com.pig4cloud.pig.codegen.service.GenTemplateGroupService; -import com.pig4cloud.pig.codegen.util.vo.GroupVo; +import com.pig4cloud.pig.codegen.util.vo.GroupVO; import com.pig4cloud.pig.codegen.util.vo.TemplateGroupDTO; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -87,7 +87,7 @@ public class GenGroupServiceImpl extends ServiceImpl tableFieldList) { AtomicInteger sort = new AtomicInteger(); this.updateBatchById(tableFieldList.stream() diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java index 9c11e95e..706031b1 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTableServiceImpl.java @@ -16,39 +16,41 @@ */ package com.pig4cloud.pig.codegen.service.impl; -import cn.hutool.core.io.IoUtil; -import cn.hutool.core.io.resource.ClassPathResource; -import cn.hutool.core.map.MapUtil; +import cn.hutool.core.collection.CollUtil; import cn.hutool.core.text.NamingCase; import cn.hutool.core.util.EnumUtil; -import cn.hutool.json.JSONObject; -import cn.hutool.json.JSONUtil; +import cn.hutool.core.util.StrUtil; import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder; import com.baomidou.mybatisplus.core.metadata.IPage; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties; import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenTable; import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity; import com.pig4cloud.pig.codegen.mapper.GenTableMapper; -import com.pig4cloud.pig.codegen.mapper.GeneratorMapper; import com.pig4cloud.pig.codegen.service.GenGroupService; import com.pig4cloud.pig.codegen.service.GenTableColumnService; import com.pig4cloud.pig.codegen.service.GenTableService; +import com.pig4cloud.pig.codegen.util.AutoFillEnum; import com.pig4cloud.pig.codegen.util.BoolFillEnum; import com.pig4cloud.pig.codegen.util.CommonColumnFiledEnum; import com.pig4cloud.pig.codegen.util.GenKit; -import com.pig4cloud.pig.codegen.util.GeneratorTypeEnum; import lombok.RequiredArgsConstructor; +import org.anyline.metadata.Column; +import org.anyline.metadata.Database; +import org.anyline.metadata.Table; +import org.anyline.proxy.ServiceProxy; +import org.anyline.service.AnylineService; +import org.jetbrains.annotations.NotNull; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; /** @@ -61,146 +63,194 @@ import java.util.Objects; @RequiredArgsConstructor public class GenTableServiceImpl extends ServiceImpl implements GenTableService { - /** - * 默认配置信息 - */ - private static final String CONFIG_PATH = "template/config.json"; + private final PigCodeGenDefaultProperties configurationProperties; - private final GenTableColumnService columnService; + private final GenTableColumnService columnService; - private final GenGroupService genGroupService; + private final GenGroupService genGroupService; - /** - * 获取配置信息 - * @return - */ - @Override - public Map getGeneratorConfig() { - ClassPathResource classPathResource = new ClassPathResource(CONFIG_PATH); - JSONObject jsonObject = JSONUtil.parseObj(IoUtil.readUtf8(classPathResource.getStream())); - return jsonObject.getRaw(); - } + /** + * 查询表ddl 语句 + * + * @param dsName 数据源名称 + * @param tableName 表名称 + * @return ddl 语句 + * @throws Exception + */ + @Override + public String queryTableDdl(String dsName, String tableName) throws Exception { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + Table table = ServiceProxy.metadata().table(tableName); // 获取表结构 + table.execute(false);// 不执行SQL + ServiceProxy.ddl().create(table); + return table.getDdl();// 返回创建表的DDL + } - @Override - public List> queryDsAllTable(String dsName) { - GeneratorMapper mapper = GenKit.getMapper(dsName); - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); - return mapper.queryTable(); - } + /** + * 查询表的全部字段 + * + * @param dsName 数据源 + * @param tableName 表名称 + * @return column + */ + @Override + public List queryTableColumn(String dsName, String tableName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + return ServiceProxy.metadata().columns(tableName).values().stream().map(Column::getName).toList(); + } - @Override - public List> queryColumn(String dsName, String tableName) { - GeneratorMapper mapper = GenKit.getMapper(dsName); - return mapper.selectMapTableColumn(tableName, dsName); - } + /** + * 查询对应数据源的表 + * + * @param page 分页信息 + * @param table 查询条件 + * @return 表 + */ + @Override + public IPage queryTablePage(Page
page, GenTable table) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(table.getDsName()); + List
tableList = ServiceProxy.metadata().tables().values().stream().filter(t -> { + if (StrUtil.isBlank(table.getTableName())) { + return true; + } + return StrUtil.containsIgnoreCase(t.getName(false), table.getTableName()); + }).toList(); - @Override - public IPage list(Page page, GenTable table) { - GeneratorMapper mapper = GenKit.getMapper(table.getDsName()); - // 手动切换数据源 - DynamicDataSourceContextHolder.push(table.getDsName()); - return mapper.queryTable(page, table.getTableName()); - } + // 根据 page 进行分页 + List
records = CollUtil.page((int) page.getCurrent() - 1, (int) page.getSize(), tableList); + page.setTotal(tableList.size()); + page.setRecords(records); + return page; + } - /** - * 获取表信息 - * @param dsName - * @param tableName - * @return - */ - @Override - public GenTable queryOrBuildTable(String dsName, String tableName) { - GenTable genTable = baseMapper.selectOne( - Wrappers.lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName)); - // 如果 genTable 为空, 执行导入 - if (Objects.isNull(genTable)) { - genTable = this.tableImport(dsName, tableName); - } + /** + * 查询数据源里面的全部表 + * + * @param dsName 数据源名称 + * @return table + */ + @Override + public List queryTableList(String dsName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); + return ServiceProxy.metadata().tables().values().stream().map(Table::getName).toList(); + } - List fieldList = columnService.list(Wrappers.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, dsName) - .eq(GenTableColumnEntity::getTableName, tableName) - .orderByAsc(GenTableColumnEntity::getSort)); - genTable.setFieldList(fieldList); + /** + * 查询表信息(列),然后插入到中间表中 + * + * @param dsName 数据源 + * @param tableName 表名 + * @return GenTable + */ + @Override + public GenTable queryOrBuildTable(String dsName, String tableName) { + GenTable genTable = baseMapper.selectOne( + Wrappers.lambdaQuery().eq(GenTable::getTableName, tableName).eq(GenTable::getDsName, dsName)); + // 如果 genTable 为空, 执行导入 + if (Objects.isNull(genTable)) { + genTable = this.tableImport(dsName, tableName); + } - // 查询模板分组信息 - List groupEntities = genGroupService.list(); - genTable.setGroupList(groupEntities); - return genTable; - } + List fieldList = columnService.list(Wrappers.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, dsName) + .eq(GenTableColumnEntity::getTableName, tableName) + .orderByAsc(GenTableColumnEntity::getSort)); + genTable.setFieldList(fieldList); - @Transactional(rollbackFor = Exception.class) - public GenTable tableImport(String dsName, String tableName) { - GeneratorMapper mapper = GenKit.getMapper(dsName); - // 手动切换数据源 - DynamicDataSourceContextHolder.push(dsName); + // 查询模板分组信息 + List groupEntities = genGroupService.list(); + genTable.setGroupList(groupEntities); + return genTable; + } - // 查询表是否存在 - GenTable table = new GenTable(); + @Transactional(rollbackFor = Exception.class) + protected GenTable tableImport(String dsName, String tableName) { + // 手动切换数据源 + DynamicDataSourceContextHolder.push(dsName); - // 从数据库获取表信息 - Map queryTable = mapper.queryTable(tableName, dsName); + // 查询表是否存在 + GenTable table = new GenTable(); + // 从数据库获取表信息 + AnylineService service = ServiceProxy.service(); + Table tableMetadata = service.metadata().table(tableName); + Database database = service.metadata().database(); + // 获取默认表配置信息 () - // 获取默认表配置信息 () - Map generatorConfig = getGeneratorConfig(); - JSONObject project = (JSONObject) generatorConfig.get("project"); - JSONObject developer = (JSONObject) generatorConfig.get("developer"); + table.setPackageName(configurationProperties.getPackageName()); + table.setVersion(configurationProperties.getVersion()); + table.setBackendPath(configurationProperties.getBackendPath()); + table.setFrontendPath(configurationProperties.getFrontendPath()); + table.setAuthor(configurationProperties.getAuthor()); + table.setEmail(configurationProperties.getEmail()); + table.setTableName(tableName); + table.setDsName(dsName); + table.setTableComment(tableMetadata.getComment()); - table.setPackageName(project.getStr("packageName")); - table.setVersion(project.getStr("version")); - table.setBackendPath(project.getStr("backendPath")); - table.setFrontendPath(project.getStr("frontendPath")); - table.setAuthor(developer.getStr("author")); - table.setEmail(developer.getStr("email")); - table.setTableName(tableName); - table.setDsName(dsName); - table.setTableComment(MapUtil.getStr(queryTable, "tableComment")); - table.setDbType(MapUtil.getStr(queryTable, "dbType")); - table.setFormLayout(2); - table.setGeneratorType(GeneratorTypeEnum.ZIP_DOWNLOAD.getValue()); - table.setClassName(NamingCase.toPascalCase(tableName)); - table.setModuleName(GenKit.getModuleName(table.getPackageName())); - table.setFunctionName(GenKit.getFunctionName(tableName)); - table.setCreateTime(LocalDateTime.now()); - this.save(table); + table.setDbType(database.getDatabase().title()); + table.setFormLayout(configurationProperties.getFormLayout()); + table.setGeneratorType(configurationProperties.getGeneratorType()); + table.setClassName(NamingCase.toPascalCase(tableName)); + // 模块名称默认为 admin + table.setModuleName(configurationProperties.getModuleName()); + table.setFunctionName(GenKit.getFunctionName(tableName)); + table.setCreateTime(LocalDateTime.now()); - // 获取原生字段数据 - List> queryColumnList = mapper.selectMapTableColumn(tableName, dsName); - List tableFieldList = new ArrayList<>(); + // 使用默认数据源 + DynamicDataSourceContextHolder.clear(); + this.save(table); - for (Map columnMap : queryColumnList) { - String columnName = MapUtil.getStr(columnMap, "columnName"); - GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity(); - genTableColumnEntity.setTableName(tableName); - genTableColumnEntity.setDsName(dsName); - genTableColumnEntity.setFieldName(MapUtil.getStr(columnMap, "columnName")); - genTableColumnEntity.setFieldComment(MapUtil.getStr(columnMap, "comments")); - genTableColumnEntity.setFieldType(MapUtil.getStr(columnMap, "dataType")); - String columnKey = MapUtil.getStr(columnMap, "columnKey"); - genTableColumnEntity.setAutoFill("DEFAULT"); - genTableColumnEntity.setPrimaryPk((StringUtils.isNotBlank(columnKey) && "PRI".equalsIgnoreCase(columnKey)) - ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue()); - genTableColumnEntity.setAutoFill("DEFAULT"); - genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue()); - genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue()); + // 获取原生字段数据 + List tableFieldList = getGenTableColumnEntities(dsName, tableName, tableMetadata); - // 审计字段处理 - if (EnumUtil.contains(CommonColumnFiledEnum.class, columnName)) { - CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(columnName); - genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem()); - genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem()); - genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill()); - genTableColumnEntity.setSort(commonColumnFiledEnum.getSort()); - } - tableFieldList.add(genTableColumnEntity); - } - // 初始化字段数据 - columnService.initFieldList(tableFieldList); - // 保存列数据 - columnService.saveOrUpdateBatch(tableFieldList); - table.setFieldList(tableFieldList); - return table; - } + // 初始化字段数据 + columnService.initFieldList(tableFieldList); + // 保存列数据 + columnService.saveOrUpdateBatch(tableFieldList); + + table.setFieldList(tableFieldList); + return table; + } + + /** + * 获取表字段信息 + * + * @param dsName 数据源信息 + * @param tableName 表名称 + * @param tableMetadata 表的元数据 + * @return list + */ + private static @NotNull List getGenTableColumnEntities(String dsName, String tableName, + Table tableMetadata) { + List tableFieldList = new ArrayList<>(); + LinkedHashMap columns = tableMetadata.getColumns(); + columns.forEach((columnName, column) -> { + GenTableColumnEntity genTableColumnEntity = new GenTableColumnEntity(); + genTableColumnEntity.setTableName(tableName); + genTableColumnEntity.setDsName(dsName); + genTableColumnEntity.setFieldName(column.getName()); + genTableColumnEntity.setFieldComment(column.getComment()); + genTableColumnEntity.setFieldType(column.getTypeName()); + genTableColumnEntity.setPrimaryPk( + column.isPrimaryKey() == 1 ? BoolFillEnum.TRUE.getValue() : BoolFillEnum.FALSE.getValue()); + genTableColumnEntity.setAutoFill(AutoFillEnum.DEFAULT.name()); + genTableColumnEntity.setFormItem(BoolFillEnum.TRUE.getValue()); + genTableColumnEntity.setGridItem(BoolFillEnum.TRUE.getValue()); + + // 审计字段处理 + if (EnumUtil.contains(CommonColumnFiledEnum.class, column.getName())) { + CommonColumnFiledEnum commonColumnFiledEnum = CommonColumnFiledEnum.valueOf(column.getName()); + genTableColumnEntity.setFormItem(commonColumnFiledEnum.getFormItem()); + genTableColumnEntity.setGridItem(commonColumnFiledEnum.getGridItem()); + genTableColumnEntity.setAutoFill(commonColumnFiledEnum.getAutoFill()); + genTableColumnEntity.setSort(commonColumnFiledEnum.getSort()); + } + tableFieldList.add(genTableColumnEntity); + }); + return tableFieldList; + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java index 45d4f4d6..ad760441 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GenTemplateServiceImpl.java @@ -16,11 +16,35 @@ */ package com.pig4cloud.pig.codegen.service.impl; +import cn.hutool.core.util.StrUtil; +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import cn.hutool.http.HttpStatus; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import cn.smallbun.screw.core.constant.DefaultConstants; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties; +import com.pig4cloud.pig.codegen.entity.GenGroupEntity; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; +import com.pig4cloud.pig.codegen.entity.GenTemplateGroupEntity; +import com.pig4cloud.pig.codegen.mapper.GenGroupMapper; +import com.pig4cloud.pig.codegen.mapper.GenTemplateGroupMapper; import com.pig4cloud.pig.codegen.mapper.GenTemplateMapper; import com.pig4cloud.pig.codegen.service.GenTemplateService; +import com.pig4cloud.pig.codegen.util.vo.GenTemplateFileVO; +import com.pig4cloud.pig.common.core.exception.CheckedException; +import com.pig4cloud.pig.common.core.util.R; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; /** * 模板 @@ -28,8 +52,147 @@ import org.springframework.stereotype.Service; * @author PIG * @date 2023-02-21 11:08:43 */ +@Slf4j @Service +@RequiredArgsConstructor public class GenTemplateServiceImpl extends ServiceImpl - implements GenTemplateService { + implements GenTemplateService { + private final GenTemplateGroupMapper genTemplateGroupMapper; + + private final GenGroupMapper genGroupMapper; + + private final PigCodeGenDefaultProperties defaultProperties; + + /** + * 在线更新 + * + * @return {@link R } + */ + @Override + @Transactional(rollbackFor = Exception.class) + public R onlineUpdate() { + // 获取 config.json 和 version 文件 + Map configAndVersion = getConfigAndVersion(); + JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); + String versionFile = (String) configAndVersion.get("versionFile"); + + // 查询出全部的模板组名称 + Set cgtmConfigGroupNames = configJsonObj.keySet(); + + String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); + // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 + boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() + .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); + + if (exists) { + return R.failed("已是最新版本,无需更新!"); + } + + // 插入新的模板组(名称 + VERSION), 再解析 config.json group 里面的所有模板 + insertTemplateFiles(versionFile, configJsonObj, cgtmConfigGroupName); + return R.ok("更新成功,版本号:" + versionFile); + } + + /** + * 检查版本 + * + * @return {@link R } + */ + public R checkVersion() { + // 关闭在线更新提示 + if (!defaultProperties.isAutoCheckVersion()) { + return R.ok(true); + } + + // 获取 config.json 和 version 文件 + Map configAndVersion = getConfigAndVersion(); + JSONObject configJsonObj = (JSONObject) configAndVersion.get("configJsonObj"); + String versionFile = (String) configAndVersion.get("versionFile"); + + // 查询出全部的模板组名称 + Set cgtmConfigGroupNames = configJsonObj.keySet(); + + String cgtmConfigGroupName = cgtmConfigGroupNames.iterator().next(); + // 根据模板组名称+version 查询是否存在,不存在则新增,存在跳过 + boolean exists = genGroupMapper.exists(Wrappers.lambdaQuery() + .eq(GenGroupEntity::getGroupName, cgtmConfigGroupName + versionFile)); + + return R.ok(exists); + } + + /** + * 获取配置和版本 + * + * @return {@link Map }<{@link String }, {@link Object }> + */ + private Map getConfigAndVersion() { + // 获取 config.json 和 version 文件 + String configFile = getCGTMFile("config.json"); + String versionFile = getCGTMFile("VERSION"); + + // 解析 config.json + JSONObject configJsonObj = JSONUtil.parseObj(configFile); + + // 将 configJsonObj 和 versionFile 放入 Map 中 + Map configAndVersion = new HashMap<>(); + configAndVersion.put("configJsonObj", configJsonObj); + configAndVersion.put("versionFile", versionFile); + + return configAndVersion; + } + + /** + * 插入模板文件 + * + * @param version 版本 + * @param configJsonObj config.json + * @param groupName 组名称 + */ + private void insertTemplateFiles(String version, JSONObject configJsonObj, String groupName) { + // 创建新的 group + GenGroupEntity genGroupEntity = new GenGroupEntity(); + genGroupEntity.setGroupName(groupName + version); + genGroupMapper.insert(genGroupEntity); + + // 解析json配置文件 + List templateFileVOList = configJsonObj.getBeanList(groupName, GenTemplateFileVO.class); + for (GenTemplateFileVO genTemplateFileVO : templateFileVOList) { + // 1. 获取模板文件 + String templateFile = getCGTMFile(genTemplateFileVO.getTemplateFile()); + + // 2. 插入模板文件 + GenTemplateEntity genTemplateEntity = new GenTemplateEntity(); + genTemplateEntity.setTemplateName(genTemplateFileVO.getTemplateName() + version); + genTemplateEntity.setTemplateDesc(genTemplateFileVO.getTemplateName() + version); + genTemplateEntity.setTemplateCode(templateFile); + genTemplateEntity.setGeneratorPath(genTemplateFileVO.getGeneratorPath()); + baseMapper.insert(genTemplateEntity); + + // 3. 插入模板组关联 + GenTemplateGroupEntity genTemplateGroupEntity = new GenTemplateGroupEntity(); + genTemplateGroupEntity.setTemplateId(genTemplateEntity.getId()); + genTemplateGroupEntity.setGroupId(genGroupEntity.getId()); + genTemplateGroupMapper.insert(genTemplateGroupEntity); + } + } + + + /** + * 获取 cgtmfile + * + * @param fileName 文件名 + * @return {@link String } + */ + private String getCGTMFile(String fileName) { + HttpResponse response = HttpRequest.get(String.format("%s/CGTM/raw/master/%s", DefaultConstants.CGTM_URL, fileName)) + .execute(); + + if (response.getStatus() == HttpStatus.HTTP_OK || StrUtil.isNotBlank(response.body())) { + return response.body(); + } else { + log.warn("在线更新模板失败:{} ,Http Code:{}", fileName, response.getStatus()); + throw new CheckedException("在线更新模板失败,任务终止!"); + } + } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java index d5f619a7..3e1d7d11 100755 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/service/impl/GeneratorServiceImpl.java @@ -21,22 +21,22 @@ import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.IoUtil; +import cn.hutool.core.text.NamingCase; import cn.hutool.core.util.BooleanUtil; import cn.hutool.core.util.StrUtil; -import cn.hutool.json.JSONObject; +import com.pig4cloud.pig.codegen.config.PigCodeGenDefaultProperties; import com.pig4cloud.pig.codegen.entity.GenTable; import com.pig4cloud.pig.codegen.entity.GenTableColumnEntity; import com.pig4cloud.pig.codegen.entity.GenTemplateEntity; import com.pig4cloud.pig.codegen.service.*; import com.pig4cloud.pig.codegen.util.VelocityKit; -import com.pig4cloud.pig.codegen.util.vo.GroupVo; +import com.pig4cloud.pig.codegen.util.vo.GroupVO; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringBootVersion; import org.springframework.stereotype.Service; -import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -56,208 +56,237 @@ import java.util.zip.ZipOutputStream; @RequiredArgsConstructor public class GeneratorServiceImpl implements GeneratorService { - private final GenTableColumnService columnService; + private final PigCodeGenDefaultProperties configurationProperties; - private final GenFieldTypeService fieldTypeService; + private final GenTableColumnService columnService; - private final GenTableService tableService; + private final GenFieldTypeService fieldTypeService; - private final GenGroupService genGroupService; + private final GenTableService tableService; - /** - * 生成代码zip写出 - * @param tableId 表 - * @param zip 输出流 - */ - @Override - @SneakyThrows - public void downloadCode(Long tableId, ZipOutputStream zip) { - // 数据模型 - Map dataModel = getDataModel(tableId); + private final GenGroupService genGroupService; - Long style = (Long) dataModel.get("style"); - GroupVo groupVo = genGroupService.getGroupVoById(style); - List templateList = groupVo.getTemplateList(); + /** + * 生成代码zip写出 + * + * @param tableId 表 + * @param zip 输出流 + */ + @Override + @SneakyThrows + public void downloadCode(Long tableId, ZipOutputStream zip) { + // 数据模型 + Map dataModel = getDataModel(tableId); - Map generatorConfig = tableService.getGeneratorConfig(); - JSONObject project = (JSONObject) generatorConfig.get("project"); - String frontendPath = project.getStr("frontendPath"); - String backendPath = project.getStr("backendPath"); + Long style = (Long) dataModel.get("style"); - for (GenTemplateEntity template : templateList) { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); + GroupVO groupVo = genGroupService.getGroupVoById(style); + List templateList = groupVo.getTemplateList(); - dataModel.put("frontendPath", frontendPath); - dataModel.put("backendPath", backendPath); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); + String frontendPath = configurationProperties.getFrontendPath(); + String backendPath = configurationProperties.getBackendPath(); - // 添加到zip - zip.putNextEntry(new ZipEntry(path)); - IoUtil.writeUtf8(zip, false, content); - zip.flush(); - zip.closeEntry(); - } + for (GenTemplateEntity template : templateList) { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); - } + dataModel.put("frontendPath", frontendPath); + dataModel.put("backendPath", backendPath); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); - /** - * 表达式优化的预览代码方法 - * @param tableId 表 - * @return [{模板名称:渲染结果}] - */ - @Override - @SneakyThrows - public List> preview(Long tableId) { - // 数据模型 - Map dataModel = getDataModel(tableId); + // 添加到zip + zip.putNextEntry(new ZipEntry(path)); + IoUtil.writeUtf8(zip, false, content); + zip.flush(); + zip.closeEntry(); + } - Long style = (Long) dataModel.get("style"); + } - // 获取模板列表,Lambda 表达式简化代码 - List templateList = genGroupService.getGroupVoById(style).getTemplateList(); + /** + * 表达式优化的预览代码方法 + * + * @param tableId 表 + * @return [{模板名称:渲染结果}] + */ + @Override + @SneakyThrows + public List> preview(Long tableId) { + // 数据模型 + Map dataModel = getDataModel(tableId); - Map generatorConfig = tableService.getGeneratorConfig(); - JSONObject project = (JSONObject) generatorConfig.get("project"); - String frontendPath = project.getStr("frontendPath"); - String backendPath = project.getStr("backendPath"); + Long style = (Long) dataModel.get("style"); - return templateList.stream().map(template -> { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); + // 获取模板列表,Lambda 表达式简化代码 + List templateList = genGroupService.getGroupVoById(style).getTemplateList(); - // 预览模式下, 使用相对路径展示 - dataModel.put("frontendPath", frontendPath); - dataModel.put("backendPath", backendPath); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); + String frontendPath = configurationProperties.getFrontendPath(); + String backendPath = configurationProperties.getBackendPath(); - // 使用 map 简化代码 - return new HashMap(4) { - { - put("code", content); - put("codePath", path); - } - }; - }).collect(Collectors.toList()); - } + return templateList.stream().map(template -> { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); - /** - * 目标目录写入渲染结果方法 - * @param tableId 表 - */ - @Override - public void generatorCode(Long tableId) { - // 数据模型 - Map dataModel = getDataModel(tableId); - Long style = (Long) dataModel.get("style"); + // 预览模式下, 使用相对路径展示 + dataModel.put("frontendPath", frontendPath); + dataModel.put("backendPath", backendPath); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); - // 获取模板列表,Lambda 表达式简化代码 - List templateList = genGroupService.getGroupVoById(style).getTemplateList(); + // 使用 map 简化代码 + return new HashMap(4) { + { + put("code", content); + put("codePath", path); + } + }; + }).collect(Collectors.toList()); + } - templateList.forEach(template -> { - String templateCode = template.getTemplateCode(); - String generatorPath = template.getGeneratorPath(); - String content = VelocityKit.renderStr(templateCode, dataModel); - String path = VelocityKit.renderStr(generatorPath, dataModel); - FileUtil.writeUtf8String(content, path); - }); - } + /** + * 目标目录写入渲染结果方法 + * + * @param tableId 表 + */ + @Override + public void generatorCode(Long tableId) { + // 数据模型 + Map dataModel = getDataModel(tableId); + Long style = (Long) dataModel.get("style"); - /** - * 通过 Lambda 表达式优化的获取数据模型方法 - * @param tableId 表格 ID - * @return 数据模型 Map 对象 - */ - private Map getDataModel(Long tableId) { - // 获取表格信息 - GenTable table = tableService.getById(tableId); - // 获取字段列表 - List fieldList = columnService.lambdaQuery() - .eq(GenTableColumnEntity::getDsName, table.getDsName()) - .eq(GenTableColumnEntity::getTableName, table.getTableName()) - .orderByAsc(GenTableColumnEntity::getSort) - .list(); + // 获取模板列表,Lambda 表达式简化代码 + List templateList = genGroupService.getGroupVoById(style).getTemplateList(); - table.setFieldList(fieldList); + templateList.forEach(template -> { + String templateCode = template.getTemplateCode(); + String generatorPath = template.getGeneratorPath(); + String content = VelocityKit.renderStr(templateCode, dataModel); + String path = VelocityKit.renderStr(generatorPath, dataModel); + FileUtil.writeUtf8String(content, path); + }); + } - // 创建数据模型对象 - Map dataModel = new HashMap<>(); - // 填充数据模型 - dataModel.put("isSpringBoot3", isSpringBoot3()); - dataModel.put("dbType", table.getDbType()); - dataModel.put("package", table.getPackageName()); - dataModel.put("packagePath", table.getPackageName().replace(".", File.separator)); - dataModel.put("version", table.getVersion()); - dataModel.put("moduleName", table.getModuleName()); - dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName())); - dataModel.put("functionName", table.getFunctionName()); - dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName())); - dataModel.put("formLayout", table.getFormLayout()); - dataModel.put("style", table.getStyle()); - dataModel.put("author", table.getAuthor()); - dataModel.put("datetime", DateUtil.now()); - dataModel.put("date", DateUtil.today()); - setFieldTypeList(dataModel, table); + /** + * 通过 Lambda 表达式优化的获取数据模型方法 + * + * @param tableId 表格 ID + * @return 数据模型 Map 对象 + */ + private Map getDataModel(Long tableId) { + // 获取表格信息 + GenTable table = tableService.getById(tableId); + // 获取字段列表 + List fieldList = columnService.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, table.getDsName()) + .eq(GenTableColumnEntity::getTableName, table.getTableName()) + .orderByAsc(GenTableColumnEntity::getSort) + .list(); - // 获取导入的包列表 - Set importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName()); - dataModel.put("importList", importList); - dataModel.put("tableName", table.getTableName()); - dataModel.put("tableComment", table.getTableComment()); - dataModel.put("className", StrUtil.lowerFirst(table.getClassName())); - dataModel.put("ClassName", table.getClassName()); - dataModel.put("fieldList", table.getFieldList()); + table.setFieldList(fieldList); - dataModel.put("backendPath", table.getBackendPath()); - dataModel.put("frontendPath", table.getFrontendPath()); - return dataModel; - } + // 创建数据模型对象 + Map dataModel = new HashMap<>(); - /** - * 将表字段按照类型分组并存储到数据模型中 - * @param dataModel 存储数据的 Map 对象 - * @param table 表信息对象 - */ - private void setFieldTypeList(Map dataModel, GenTable table) { - // 按字段类型分组,使用 Map 存储不同类型的字段列表 - Map> typeMap = table.getFieldList() - .stream() - .collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk()))); + // 填充数据模型 + dataModel.put("isSpringBoot3", isSpringBoot3()); + dataModel.put("dbType", table.getDbType()); + dataModel.put("package", table.getPackageName()); + dataModel.put("packagePath", table.getPackageName().replace(".", "/")); + dataModel.put("version", table.getVersion()); + dataModel.put("moduleName", table.getModuleName()); + dataModel.put("ModuleName", StrUtil.upperFirst(table.getModuleName())); + dataModel.put("functionName", table.getFunctionName()); + dataModel.put("FunctionName", StrUtil.upperFirst(table.getFunctionName())); + dataModel.put("formLayout", table.getFormLayout()); + dataModel.put("style", table.getStyle()); + dataModel.put("author", table.getAuthor()); + dataModel.put("datetime", DateUtil.now()); + dataModel.put("date", DateUtil.today()); + setFieldTypeList(dataModel, table); - // 从分组后的 Map 中获取不同类型的字段列表 - List primaryList = typeMap.get(true); - List formList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem())) - .collect(Collectors.toList()); - List gridList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem())) - .collect(Collectors.toList()); - List queryList = typeMap.get(false) - .stream() - .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem())) - .collect(Collectors.toList()); + // 获取导入的包列表 + Set importList = fieldTypeService.getPackageByTableId(table.getDsName(), table.getTableName()); + dataModel.put("importList", importList); + dataModel.put("tableName", table.getTableName()); + dataModel.put("tableComment", table.getTableComment()); + dataModel.put("className", StrUtil.lowerFirst(table.getClassName())); + dataModel.put("ClassName", table.getClassName()); + dataModel.put("fieldList", table.getFieldList()); - if (CollUtil.isNotEmpty(primaryList)) { - dataModel.put("pk", primaryList.get(0)); - } - dataModel.put("primaryList", primaryList); - dataModel.put("formList", formList); - dataModel.put("gridList", gridList); - dataModel.put("queryList", queryList); - } + dataModel.put("backendPath", table.getBackendPath()); + dataModel.put("frontendPath", table.getFrontendPath()); + + // 设置子表 + String childTableName = table.getChildTableName(); + if (StrUtil.isNotBlank(childTableName)) { + List childFieldList = columnService.lambdaQuery() + .eq(GenTableColumnEntity::getDsName, table.getDsName()) + .eq(GenTableColumnEntity::getTableName, table.getChildTableName()) + .list(); + dataModel.put("childFieldList", childFieldList); + dataModel.put("childTableName", childTableName); + dataModel.put("mainField", NamingCase.toCamelCase(table.getMainField())); + dataModel.put("childField", NamingCase.toCamelCase(table.getChildField())); + dataModel.put("ChildClassName", NamingCase.toPascalCase(childTableName)); + dataModel.put("childClassName", StrUtil.lowerFirst(NamingCase.toPascalCase(childTableName))); + // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) + childFieldList.stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) + .findFirst().ifPresent(columnEntity -> dataModel.put("isChildTenant", true)); + } + + // 设置是否是多租户模式 (判断字段列表中是否包含 tenant_id 字段) + table.getFieldList().stream().filter(genTableColumnEntity -> genTableColumnEntity.getFieldName().equals("tenant_id")) + .findFirst().ifPresent(columnEntity -> dataModel.put("isTenant", true)); + + return dataModel; + } + + /** + * 判断当前是否是 SpringBoot3 版本 + * + * @return true/fasle + */ + private boolean isSpringBoot3() { + return StrUtil.startWith(SpringBootVersion.getVersion(), "3"); + } + + /** + * 将表字段按照类型分组并存储到数据模型中 + * + * @param dataModel 存储数据的 Map 对象 + * @param table 表信息对象 + */ + private void setFieldTypeList(Map dataModel, GenTable table) { + // 按字段类型分组,使用 Map 存储不同类型的字段列表 + Map> typeMap = table.getFieldList() + .stream() + .collect(Collectors.partitioningBy(columnEntity -> BooleanUtil.toBoolean(columnEntity.getPrimaryPk()))); + + // 从分组后的 Map 中获取不同类型的字段列表 + List primaryList = typeMap.get(true); + List formList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getFormItem())) + .collect(Collectors.toList()); + List gridList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getGridItem())) + .collect(Collectors.toList()); + List queryList = typeMap.get(false) + .stream() + .filter(columnEntity -> BooleanUtil.toBoolean(columnEntity.getQueryItem())) + .collect(Collectors.toList()); + + if (CollUtil.isNotEmpty(primaryList)) { + dataModel.put("pk", primaryList.get(0)); + } + dataModel.put("primaryList", primaryList); + dataModel.put("formList", formList); + dataModel.put("gridList", gridList); + dataModel.put("queryList", queryList); + } - /** - * 判断当前是否是 SpringBoot3 版本 - * - * @return true/fasle - */ - private boolean isSpringBoot3() { - return StrUtil.startWith(SpringBootVersion.getVersion(), "3"); - } } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/AutoFillEnum.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/AutoFillEnum.java new file mode 100644 index 00000000..5bc1471f --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/AutoFillEnum.java @@ -0,0 +1,12 @@ +package com.pig4cloud.pig.codegen.util; + +/** + * 字段自动填充 枚举 + * + * @author 阿沐 babamu@126.com + */ +public enum AutoFillEnum { + + DEFAULT, INSERT, UPDATE, INSERT_UPDATE, CREATE; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/CommonColumnFiledEnum.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/CommonColumnFiledEnum.java index 5ef0f830..7f7545f4 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/CommonColumnFiledEnum.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/CommonColumnFiledEnum.java @@ -16,36 +16,36 @@ public enum CommonColumnFiledEnum { /** * create_by 字段 */ - create_by("0", "0", "INSERT", 100), + create_by("0", "0", AutoFillEnum.INSERT.name(), 100), /** * create_time 字段 */ - create_time("0", "0", "INSERT", 101), + create_time("0", "0", AutoFillEnum.INSERT.name(), 101), /** * update_by 字段 */ - update_by("0", "0", "INSERT_UPDATE", 102), + update_by("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 102), /** * update_time 字段 */ - update_time("0", "0", "INSERT_UPDATE", 103), + update_time("0", "0", AutoFillEnum.INSERT_UPDATE.name(), 103), /** * del_flag 字段 */ - del_flag("0", "0", "DEFAULT", 104), + del_flag("0", "0", AutoFillEnum.DEFAULT.name(), 104), /** * tenant_id 字段 */ - tenant_id("0", "0", "DEFAULT", 105); + tenant_id("0", "0", AutoFillEnum.DEFAULT.name(), 105); /** - * 表单是否默认显示 + * 表单是否默认显示 1/0 */ private String formItem; /** - * 表格是否默认显示 + * 表格是否默认显示 1/0 */ private String gridItem; diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenKit.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenKit.java index 057c4165..4ac3a1a6 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenKit.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GenKit.java @@ -1,16 +1,7 @@ package com.pig4cloud.pig.codegen.util; import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.core.toolkit.Wrappers; -import com.pig4cloud.pig.codegen.entity.GenDatasourceConf; -import com.pig4cloud.pig.codegen.mapper.GenDatasourceConfMapper; -import com.pig4cloud.pig.codegen.mapper.GeneratorMapper; -import com.pig4cloud.pig.common.core.util.SpringContextHolder; -import com.pig4cloud.pig.common.datasource.enums.DsJdbcUrlEnum; import lombok.experimental.UtilityClass; -import org.springframework.context.ApplicationContext; - -import java.util.Map; /** * 代码生成工具类 @@ -39,37 +30,4 @@ public class GenKit { return StrUtil.subAfter(packageName, ".", true); } - /** - * 获取数据源对应方言的mapper - * @param dsName 数据源名称 - * @return GeneratorMapper - */ - public GeneratorMapper getMapper(String dsName) { - // 获取目标数据源数据库类型 - GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class); - GenDatasourceConf datasourceConf = datasourceConfMapper - .selectOne(Wrappers.lambdaQuery().eq(GenDatasourceConf::getName, dsName)); - - String dbConfType; - // 默认MYSQL 数据源 - if (datasourceConf == null) { - dbConfType = DsJdbcUrlEnum.MYSQL.getDbName(); - } - else { - dbConfType = datasourceConf.getDsType(); - } - // 获取全部数据实现 - ApplicationContext context = SpringContextHolder.getApplicationContext(); - Map beansOfType = context.getBeansOfType(GeneratorMapper.class); - - // 根据数据类型选择mapper - for (String key : beansOfType.keySet()) { - if (StrUtil.containsIgnoreCase(key, dbConfType)) { - return beansOfType.get(key); - } - } - - throw new IllegalArgumentException("dsName 不合法: " + dsName); - } - } diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorStyleEnum.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorStyleEnum.java new file mode 100644 index 00000000..e05fc50e --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorStyleEnum.java @@ -0,0 +1,29 @@ +package com.pig4cloud.pig.codegen.util; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * 代码生成主题 + * + * @author 冷冷 + */ +@Getter +@AllArgsConstructor +public enum GeneratorStyleEnum { + + VFORM_JSON(1L, "element-plus 风格"), + + VFORM_FORM(2L, "uview 风格"); + + /** + * 对应模板ID + */ + private Long templateId; + + /** + * 描述 + */ + private String desc; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorTypeEnum.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorTypeEnum.java deleted file mode 100644 index e991e883..00000000 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/GeneratorTypeEnum.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.pig4cloud.pig.codegen.util; - -import lombok.Getter; -import lombok.RequiredArgsConstructor; - -@Getter -@RequiredArgsConstructor -public enum GeneratorTypeEnum { - - /** - * zip压缩包 0 - */ - ZIP_DOWNLOAD("0"), - /** - * 自定义目录 1 - */ - CUSTOM_DIRECTORY("1"); - - private final String value; - -} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormConfigConsts.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormConfigConsts.java new file mode 100644 index 00000000..e6c6daee --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormConfigConsts.java @@ -0,0 +1,25 @@ +package com.pig4cloud.pig.codegen.util; + +/** + * vform 的通用变量 + * + * @author lengleng + * @date 2023/6/5 + */ +public interface VFormConfigConsts { + + String widgetList = "widgetList"; + + String groupKey = "groupKey"; + + String type = "type"; + + String options = "options"; + + String span = "span"; + + String cols = "cols"; + + String key = "key"; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormTypeEnum.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormTypeEnum.java new file mode 100644 index 00000000..840fea18 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/VFormTypeEnum.java @@ -0,0 +1,22 @@ +package com.pig4cloud.pig.codegen.util; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +/** + * vfrom 字段类型 + * + * @author lengleng + * @date 2023/6/5 + */ +@Getter +@AllArgsConstructor +public enum VFormTypeEnum { + + GRID("grid"), + + GRID_COL("grid-col"); + + private final String type; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenCreateTableVO.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenCreateTableVO.java new file mode 100755 index 00000000..fac44fd2 --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenCreateTableVO.java @@ -0,0 +1,95 @@ +package com.pig4cloud.pig.codegen.util.vo; +/* + * Copyright (c) 2018-2025, luolin All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * Neither the name of the pig4cloud.com developer nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * Author: luolin (766488893@qq.com) + */ + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.time.LocalDateTime; + +/** + * 自动创建表管理 + * + * @author luolin + * @date 2022-09-23 21:56:11 + */ +@Data +@Schema(description = "自动创建表管理") +public class GenCreateTableVO { + + private static final long serialVersionUID = 1L; + + /** + * 主键ID + */ + @Schema(description = "主键ID") + private Long id; + + /** + * 表名称 + */ + @NotBlank(message = "表名称不能为空") + @Schema(description = "表名称") + private String tableName; + + /** + * 表注释 + */ + @NotBlank(message = "表注释不能为空") + @Schema(description = "表注释") + private String comments; + + /** + * 数据源名称 + */ + @NotBlank(message = "数据源名称不能为空") + @Schema(description = "数据源名称") + private String dsName; + + /** + * 主键策略 + */ + @NotBlank(message = "主键策略不能为空") + @Schema(description = "主键策略") + private String pkPolicy; + + /** + * 创建人 + */ + @Schema(description = "创建人") + private Long createUser; + + /** + * 创建时间 + */ + @Schema(description = "创建时间") + private LocalDateTime createTime; + + /** + * 表字段信息 + */ + @Schema(description = "表字段信息") + private String columnsInfo; + + /** + * 字段信息 + */ + @Schema(description = "字段信息") + private String columnInfo; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java new file mode 100644 index 00000000..5eb4413c --- /dev/null +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GenTemplateFileVO.java @@ -0,0 +1,37 @@ +package com.pig4cloud.pig.codegen.util.vo; + +import lombok.Data; + +/** + * @author lengleng + * @date 2024/7/13 + *

+ * CGTM 文件路径 + *

+ * { + * "templateName": "Controller", + * "generatorPath": "${backendPath}/src/main/java/${packagePath}/${moduleName}/controller/${ClassName}Controller.java", + * "templateDesc": "后台Controller", + * "templateFile": "temps/Controller" + * }, + */ +@Data +public class GenTemplateFileVO { + /** + * 模板名称 + */ + private String templateName; + /** + * 路径 + */ + private String generatorPath; + /** + * 模板 desc + */ + private String templateDesc; + /** + * 模板文件 + */ + private String templateFile; + +} diff --git a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVo.java b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVO.java similarity index 97% rename from pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVo.java rename to pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVO.java index 23f6abb5..e46feda9 100644 --- a/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVo.java +++ b/pig-visual/pig-codegen/src/main/java/com/pig4cloud/pig/codegen/util/vo/GroupVO.java @@ -9,7 +9,7 @@ import lombok.Data; import java.util.List; @Data -public class GroupVo { +public class GroupVO { /** * id diff --git a/pig-visual/pig-codegen/src/main/resources/mapper/GenGroupMapper.xml b/pig-visual/pig-codegen/src/main/resources/mapper/GenGroupMapper.xml index 83d36147..efc2ef0d 100644 --- a/pig-visual/pig-codegen/src/main/resources/mapper/GenGroupMapper.xml +++ b/pig-visual/pig-codegen/src/main/resources/mapper/GenGroupMapper.xml @@ -3,12 +3,12 @@ - + + select="com.pig4cloud.pig.codegen.mapper.GenTemplateMapper.listTemplateById" column="group_id"> diff --git a/pig-visual/pig-codegen/src/main/resources/mapper/GenTableMapper.xml b/pig-visual/pig-codegen/src/main/resources/mapper/GenTableMapper.xml index e9a64953..633c857f 100644 --- a/pig-visual/pig-codegen/src/main/resources/mapper/GenTableMapper.xml +++ b/pig-visual/pig-codegen/src/main/resources/mapper/GenTableMapper.xml @@ -23,7 +23,7 @@ - + @@ -38,8 +38,7 @@ - - + diff --git a/pig-visual/pig-codegen/src/main/resources/mapper/GeneratorMySqlMapper.xml b/pig-visual/pig-codegen/src/main/resources/mapper/GeneratorMySqlMapper.xml deleted file mode 100755 index ca5b9eb9..00000000 --- a/pig-visual/pig-codegen/src/main/resources/mapper/GeneratorMySqlMapper.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - - - SELECT - column_name columnName, - data_type dataType, - column_comment comments, - column_key columnKey, - extra, - is_nullable AS isNullable, - column_type AS columnType - FROM - information_schema.COLUMNS - WHERE - table_name = #{tableName} and table_schema = (select database()) order by ordinal_position - - - - - - - diff --git a/pig-visual/pig-codegen/src/main/resources/template/config.json b/pig-visual/pig-codegen/src/main/resources/template/config.json deleted file mode 100644 index 4f33f5d0..00000000 --- a/pig-visual/pig-codegen/src/main/resources/template/config.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "project": { - "packageName": "com.pig4cloud.pig", - "version": "1.0.0", - "backendPath": "pig", - "frontendPath": "pig-ui" - }, - "developer": { - "author": "pig", - "email": "pig4cloud@qq.com" - } -}