From 8f3f4384c3ef967a3dfda53ccd6a39a19638a06c Mon Sep 17 00:00:00 2001 From: ageer <ageerle@163.com> Date: 星期五, 28 三月 2025 23:00:24 +0800 Subject: [PATCH] feat(代码生成): 恢复代码生成模块 --- ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/controller.java.vm | 115 + ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/constant/GenConstants.java | 186 ++ ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/config/GenConfig.java | 73 + ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTable.java | 190 ++ ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm | 133 + ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/service.java.vm | 53 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityInitializer.java | 35 ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/types.ts.vm | 44 pom.xml | 6 ruoyi-modules/pom.xml | 1 ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/oracle/sql.vm | 19 ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sql.vm | 19 ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm | 475 ++++++ ruoyi-modules/ruoyi-generator/src/main/resources/mapper/package-info.md | 3 ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm | 15 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/GenTableServiceImpl.java | 459 ++++++ ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/bo.java.vm | 48 ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/domain.java.vm | 59 ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/api.ts.vm | 63 ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm | 502 ++++++ ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sqlserver/sql.vm | 19 ruoyi-modules/ruoyi-generator/src/main/resources/vm/js/api.js.vm | 44 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityUtils.java | 338 ++++ ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/controller/GenController.java | 207 ++ ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml | 220 +++ script/sql/ruoyi-ai.sql | 22 ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/postgres/sql.vm | 20 ruoyi-admin/pom.xml | 4 ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/vo.java.vm | 59 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTableColumn.java | 222 +++ ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/GenUtils.java | 233 +++ ruoyi-modules/ruoyi-generator/src/main/resources/generator.yml | 10 ruoyi-modules/ruoyi-generator/pom.xml | 53 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/IGenTableService.java | 133 + ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableMapper.java | 58 ruoyi-modules/ruoyi-generator/src/main/resources/vm/xml/mapper.xml.vm | 7 ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableColumnMapper.java | 24 ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml | 93 + 38 files changed, 4,253 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index 7b9dfda..27043d0 100644 --- a/pom.xml +++ b/pom.xml @@ -330,6 +330,12 @@ <dependency> <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-generator</artifactId> + <version>${revision}</version> + </dependency> + + <dependency> + <groupId>org.ruoyi</groupId> <artifactId>ruoyi-demo</artifactId> <version>${revision}</version> </dependency> diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml index a8276a4..4bbb0e3 100644 --- a/ruoyi-admin/pom.xml +++ b/ruoyi-admin/pom.xml @@ -62,6 +62,10 @@ <artifactId>ruoyi-knowledge</artifactId> </dependency> + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-generator</artifactId> + </dependency> <!-- demo妯″潡 --> <dependency> diff --git a/ruoyi-modules/pom.xml b/ruoyi-modules/pom.xml index d7696fb..8aca569 100644 --- a/ruoyi-modules/pom.xml +++ b/ruoyi-modules/pom.xml @@ -22,6 +22,7 @@ <module>ruoyi-system</module> <module>ruoyi-live</module> <module>ruoyi-knowledge</module> + <module>ruoyi-generator</module> </modules> </project> diff --git a/ruoyi-modules/ruoyi-generator/pom.xml b/ruoyi-modules/ruoyi-generator/pom.xml new file mode 100644 index 0000000..c6ab5e3 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/pom.xml @@ -0,0 +1,53 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <parent> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-modules</artifactId> + <version>${revision}</version> + <relativePath>../pom.xml</relativePath> + </parent> + <modelVersion>4.0.0</modelVersion> + + <artifactId>ruoyi-generator</artifactId> + + <description> + generator 浠g爜鐢熸垚 + </description> + + <dependencies> + <!-- 閫氱敤宸ュ叿--> + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-common-core</artifactId> + </dependency> + + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-common-doc</artifactId> + </dependency> + + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-common-mybatis</artifactId> + </dependency> + + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-common-web</artifactId> + </dependency> + + <dependency> + <groupId>org.ruoyi</groupId> + <artifactId>ruoyi-common-log</artifactId> + </dependency> + + <!--velocity浠g爜鐢熸垚浣跨敤妯℃澘 --> + <dependency> + <groupId>org.apache.velocity</groupId> + <artifactId>velocity-engine-core</artifactId> + </dependency> + </dependencies> + +</project> diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/config/GenConfig.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/config/GenConfig.java new file mode 100644 index 0000000..5530313 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/config/GenConfig.java @@ -0,0 +1,73 @@ +package org.ruoyi.generator.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +/** + * 璇诲彇浠g爜鐢熸垚鐩稿叧閰嶇疆 + * + * @author ruoyi + */ +@Component +@ConfigurationProperties(prefix = "gen") +@PropertySource(value = {"classpath:generator.yml"}, encoding = "UTF-8") +public class GenConfig { + + /** + * 浣滆�� + */ + public static String author; + + /** + * 鐢熸垚鍖呰矾寰� + */ + public static String packageName; + + /** + * 鑷姩鍘婚櫎琛ㄥ墠缂�锛岄粯璁ゆ槸false + */ + public static boolean autoRemovePre; + + /** + * 琛ㄥ墠缂�(绫诲悕涓嶄細鍖呭惈琛ㄥ墠缂�) + */ + public static String tablePrefix; + + public static String getAuthor() { + return author; + } + + @Value("${author}") + public void setAuthor(String author) { + GenConfig.author = author; + } + + public static String getPackageName() { + return packageName; + } + + @Value("${packageName}") + public void setPackageName(String packageName) { + GenConfig.packageName = packageName; + } + + public static boolean getAutoRemovePre() { + return autoRemovePre; + } + + @Value("${autoRemovePre}") + public void setAutoRemovePre(boolean autoRemovePre) { + GenConfig.autoRemovePre = autoRemovePre; + } + + public static String getTablePrefix() { + return tablePrefix; + } + + @Value("${tablePrefix}") + public void setTablePrefix(String tablePrefix) { + GenConfig.tablePrefix = tablePrefix; + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/constant/GenConstants.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/constant/GenConstants.java new file mode 100644 index 0000000..c3d2b1f --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/constant/GenConstants.java @@ -0,0 +1,186 @@ +package org.ruoyi.generator.constant; + +/** + * 浠g爜鐢熸垚閫氱敤甯搁噺 + * + * @author ruoyi + */ +public interface GenConstants { + /** + * 鍗曡〃锛堝鍒犳敼鏌ワ級 + */ + String TPL_CRUD = "crud"; + + /** + * 鏍戣〃锛堝鍒犳敼鏌ワ級 + */ + String TPL_TREE = "tree"; + + /** + * 鏍戠紪鐮佸瓧娈� + */ + String TREE_CODE = "treeCode"; + + /** + * 鏍戠埗缂栫爜瀛楁 + */ + String TREE_PARENT_CODE = "treeParentCode"; + + /** + * 鏍戝悕绉板瓧娈� + */ + String TREE_NAME = "treeName"; + + /** + * 涓婄骇鑿滃崟ID瀛楁 + */ + String PARENT_MENU_ID = "parentMenuId"; + + /** + * 涓婄骇鑿滃崟鍚嶇О瀛楁 + */ + String PARENT_MENU_NAME = "parentMenuName"; + + /** + * 鏁版嵁搴撳瓧绗︿覆绫诲瀷 + */ + String[] COLUMNTYPE_STR = {"char", "varchar", "enum", "set", "nchar", "nvarchar", "varchar2", "nvarchar2"}; + + /** + * 鏁版嵁搴撴枃鏈被鍨� + */ + String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext", "binary", "varbinary", "blob", + "ntext", "image", "bytea"}; + + /** + * 鏁版嵁搴撴椂闂寸被鍨� + */ + String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp", "year", "interval", + "smalldatetime", "datetime2", "datetimeoffset"}; + + /** + * 鏁版嵁搴撴暟瀛楃被鍨� + */ + String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer", + "bit", "bigint", "float", "double", "decimal", "numeric", "real", "double precision", + "smallserial", "serial", "bigserial", "money", "smallmoney"}; + + /** + * BO瀵硅薄 涓嶉渶瑕佹坊鍔犲瓧娈� + */ + String[] COLUMNNAME_NOT_ADD = {"create_dept", "create_by", "create_time", "del_flag", "update_by", + "update_time", "version", "tenant_id"}; + + /** + * BO瀵硅薄 涓嶉渶瑕佺紪杈戝瓧娈� + */ + String[] COLUMNNAME_NOT_EDIT = {"create_dept", "create_by", "create_time", "del_flag", "update_by", + "update_time", "version", "tenant_id"}; + + /** + * VO瀵硅薄 涓嶉渶瑕佽繑鍥炲瓧娈� + */ + String[] COLUMNNAME_NOT_LIST = {"create_dept", "create_by", "create_time", "del_flag", "update_by", + "update_time", "version", "tenant_id"}; + + /** + * BO瀵硅薄 涓嶉渶瑕佹煡璇㈠瓧娈� + */ + String[] COLUMNNAME_NOT_QUERY = {"id", "create_dept", "create_by", "create_time", "del_flag", "update_by", + "update_time", "remark", "version", "tenant_id"}; + + /** + * Entity鍩虹被瀛楁 + */ + String[] BASE_ENTITY = {"createDept", "createBy", "createTime", "updateBy", "updateTime", "tenantId"}; + + /** + * 鏂囨湰妗� + */ + String HTML_INPUT = "input"; + + /** + * 鏂囨湰鍩� + */ + String HTML_TEXTAREA = "textarea"; + + /** + * 涓嬫媺妗� + */ + String HTML_SELECT = "select"; + + /** + * 鍗曢�夋 + */ + String HTML_RADIO = "radio"; + + /** + * 澶嶉�夋 + */ + String HTML_CHECKBOX = "checkbox"; + + /** + * 鏃ユ湡鎺т欢 + */ + String HTML_DATETIME = "datetime"; + + /** + * 鍥剧墖涓婁紶鎺т欢 + */ + String HTML_IMAGE_UPLOAD = "imageUpload"; + + /** + * 鏂囦欢涓婁紶鎺т欢 + */ + String HTML_FILE_UPLOAD = "fileUpload"; + + /** + * 瀵屾枃鏈帶浠� + */ + String HTML_EDITOR = "editor"; + + /** + * 瀛楃涓茬被鍨� + */ + String TYPE_STRING = "String"; + + /** + * 鏁村瀷 + */ + String TYPE_INTEGER = "Integer"; + + /** + * 闀挎暣鍨� + */ + String TYPE_LONG = "Long"; + + /** + * 娴偣鍨� + */ + String TYPE_DOUBLE = "Double"; + + /** + * 楂樼簿搴﹁绠楃被鍨� + */ + String TYPE_BIGDECIMAL = "BigDecimal"; + + /** + * 鏃堕棿绫诲瀷 + */ + String TYPE_DATE = "Date"; + + /** + * 妯$硦鏌ヨ + */ + String QUERY_LIKE = "LIKE"; + + /** + * 鐩哥瓑鏌ヨ + */ + String QUERY_EQ = "EQ"; + + /** + * 闇�瑕� + */ + String REQUIRE = "1"; +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/controller/GenController.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/controller/GenController.java new file mode 100644 index 0000000..15cb1b7 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/controller/GenController.java @@ -0,0 +1,207 @@ +package org.ruoyi.generator.controller; + +import cn.dev33.satoken.annotation.SaCheckPermission; +import cn.hutool.core.convert.Convert; +import cn.hutool.core.io.IoUtil; +import org.ruoyi.generator.domain.GenTable; +import org.ruoyi.generator.domain.GenTableColumn; +import org.ruoyi.generator.service.IGenTableService; +import org.ruoyi.common.core.domain.R; +import org.ruoyi.common.log.annotation.Log; +import org.ruoyi.common.log.enums.BusinessType; +import org.ruoyi.common.mybatis.core.page.PageQuery; +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +import org.ruoyi.common.web.core.BaseController; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 浠g爜鐢熸垚 鎿嶄綔澶勭悊 + * + * @author Lion Li + */ +@Validated +@RequiredArgsConstructor +@RestController +@RequestMapping("/tool/gen") +public class GenController extends BaseController { + + private final IGenTableService genTableService; + + /** + * 鏌ヨ浠g爜鐢熸垚鍒楄〃 + */ + @SaCheckPermission("tool:gen:list") + @GetMapping("/list") + public TableDataInfo<GenTable> genList(GenTable genTable, PageQuery pageQuery) { + return genTableService.selectPageGenTableList(genTable, pageQuery); + } + + /** + * 淇敼浠g爜鐢熸垚涓氬姟 + * + * @param tableId 琛↖D + */ + @SaCheckPermission("tool:gen:query") + @GetMapping(value = "/{tableId}") + public R<Map<String, Object>> getInfo(@PathVariable Long tableId) { + GenTable table = genTableService.selectGenTableById(tableId); + List<GenTable> tables = genTableService.selectGenTableAll(); + List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId); + Map<String, Object> map = new HashMap<String, Object>(); + map.put("info", table); + map.put("rows", list); + map.put("tables", tables); + return R.ok(map); + } + + /** + * 鏌ヨ鏁版嵁搴撳垪琛� + */ + @SaCheckPermission("tool:gen:list") + @GetMapping("/db/list") + public TableDataInfo<GenTable> dataList(GenTable genTable, PageQuery pageQuery) { + return genTableService.selectPageDbTableList(genTable, pageQuery); + } + + /** + * 鏌ヨ鏁版嵁琛ㄥ瓧娈靛垪琛� + * + * @param tableId 琛↖D + */ + @SaCheckPermission("tool:gen:list") + @GetMapping(value = "/column/{tableId}") + public TableDataInfo<GenTableColumn> columnList(Long tableId) { + TableDataInfo<GenTableColumn> dataInfo = new TableDataInfo<>(); + List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId); + dataInfo.setRows(list); + dataInfo.setTotal(list.size()); + return dataInfo; + } + + /** + * 瀵煎叆琛ㄧ粨鏋勶紙淇濆瓨锛� + * + * @param tables 琛ㄥ悕涓� + */ + @SaCheckPermission("tool:gen:import") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.IMPORT) + @PostMapping("/importTable") + public R<Void> importTableSave(String tables) { + String[] tableNames = Convert.toStrArray(tables); + // 鏌ヨ琛ㄤ俊鎭� + List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames); + genTableService.importGenTable(tableList); + return R.ok(); + } + + /** + * 淇敼淇濆瓨浠g爜鐢熸垚涓氬姟 + */ + @SaCheckPermission("tool:gen:edit") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.UPDATE) + @PutMapping + public R<Void> editSave(@Validated @RequestBody GenTable genTable) { + genTableService.validateEdit(genTable); + genTableService.updateGenTable(genTable); + return R.ok(); + } + + /** + * 鍒犻櫎浠g爜鐢熸垚 + * + * @param tableIds 琛↖D涓� + */ + @SaCheckPermission("tool:gen:remove") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.DELETE) + @DeleteMapping("/{tableIds}") + public R<Void> remove(@PathVariable Long[] tableIds) { + genTableService.deleteGenTableByIds(tableIds); + return R.ok(); + } + + /** + * 棰勮浠g爜 + * + * @param tableId 琛↖D + */ + @SaCheckPermission("tool:gen:preview") + @GetMapping("/preview/{tableId}") + public R<Map<String, String>> preview(@PathVariable("tableId") Long tableId) throws IOException { + Map<String, String> dataMap = genTableService.previewCode(tableId); + return R.ok(dataMap); + } + + /** + * 鐢熸垚浠g爜锛堜笅杞芥柟寮忥級 + * + * @param tableName 琛ㄥ悕 + */ + @SaCheckPermission("tool:gen:code") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.GENCODE) + @GetMapping("/download/{tableName}") + public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { + byte[] data = genTableService.downloadCode(tableName); + genCode(response, data); + } + + /** + * 鐢熸垚浠g爜锛堣嚜瀹氫箟璺緞锛� + * + * @param tableName 琛ㄥ悕 + */ + @SaCheckPermission("tool:gen:code") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.GENCODE) + @GetMapping("/genCode/{tableName}") + public R<Void> genCode(@PathVariable("tableName") String tableName) { + genTableService.generatorCode(tableName); + return R.ok(); + } + + /** + * 鍚屾鏁版嵁搴� + * + * @param tableName 琛ㄥ悕 + */ + @SaCheckPermission("tool:gen:edit") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.UPDATE) + @GetMapping("/synchDb/{tableName}") + public R<Void> synchDb(@PathVariable("tableName") String tableName) { + genTableService.synchDb(tableName); + return R.ok(); + } + + /** + * 鎵归噺鐢熸垚浠g爜 + * + * @param tables 琛ㄥ悕涓� + */ + @SaCheckPermission("tool:gen:code") + @Log(title = "浠g爜鐢熸垚", businessType = BusinessType.GENCODE) + @GetMapping("/batchGenCode") + public void batchGenCode(HttpServletResponse response, String tables) throws IOException { + String[] tableNames = Convert.toStrArray(tables); + byte[] data = genTableService.downloadCode(tableNames); + genCode(response, data); + } + + /** + * 鐢熸垚zip鏂囦欢 + */ + private void genCode(HttpServletResponse response, byte[] data) throws IOException { + response.reset(); + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Access-Control-Expose-Headers", "Content-Disposition"); + response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\""); + response.addHeader("Content-Length", "" + data.length); + response.setContentType("application/octet-stream; charset=UTF-8"); + IoUtil.write(response.getOutputStream(), false, data); + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTable.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTable.java new file mode 100644 index 0000000..901d124 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTable.java @@ -0,0 +1,190 @@ +package org.ruoyi.generator.domain; + +import com.baomidou.mybatisplus.annotation.FieldStrategy; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import org.ruoyi.generator.constant.GenConstants; +import org.ruoyi.common.core.utils.StringUtils; +import org.ruoyi.common.mybatis.core.domain.BaseEntity; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; + +/** + * 涓氬姟琛� gen_table + * + * @author Lion Li + */ + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("gen_table") +public class GenTable extends BaseEntity { + + /** + * 缂栧彿 + */ + @TableId(value = "table_id") + private Long tableId; + + /** + * 琛ㄥ悕绉� + */ + @NotBlank(message = "琛ㄥ悕绉颁笉鑳戒负绌�") + private String tableName; + + /** + * 琛ㄦ弿杩� + */ + @NotBlank(message = "琛ㄦ弿杩颁笉鑳戒负绌�") + private String tableComment; + + /** + * 鍏宠仈鐖惰〃鐨勮〃鍚� + */ + private String subTableName; + + /** + * 鏈〃鍏宠仈鐖惰〃鐨勫閿悕 + */ + private String subTableFkName; + + /** + * 瀹炰綋绫诲悕绉�(棣栧瓧姣嶅ぇ鍐�) + */ + @NotBlank(message = "瀹炰綋绫诲悕绉颁笉鑳戒负绌�") + private String className; + + /** + * 浣跨敤鐨勬ā鏉匡紙crud鍗曡〃鎿嶄綔 tree鏍戣〃鎿嶄綔 sub涓诲瓙琛ㄦ搷浣滐級 + */ + private String tplCategory; + + /** + * 鐢熸垚鍖呰矾寰� + */ + @NotBlank(message = "鐢熸垚鍖呰矾寰勪笉鑳戒负绌�") + private String packageName; + + /** + * 鐢熸垚妯″潡鍚� + */ + @NotBlank(message = "鐢熸垚妯″潡鍚嶄笉鑳戒负绌�") + private String moduleName; + + /** + * 鐢熸垚涓氬姟鍚� + */ + @NotBlank(message = "鐢熸垚涓氬姟鍚嶄笉鑳戒负绌�") + private String businessName; + + /** + * 鐢熸垚鍔熻兘鍚� + */ + @NotBlank(message = "鐢熸垚鍔熻兘鍚嶄笉鑳戒负绌�") + private String functionName; + + /** + * 鐢熸垚浣滆�� + */ + @NotBlank(message = "浣滆�呬笉鑳戒负绌�") + private String functionAuthor; + + /** + * 鐢熸垚浠g爜鏂瑰紡锛�0zip鍘嬬缉鍖� 1鑷畾涔夎矾寰勶級 + */ + private String genType; + + /** + * 鐢熸垚璺緞锛堜笉濉粯璁ら」鐩矾寰勶級 + */ + @TableField(updateStrategy = FieldStrategy.NOT_EMPTY) + private String genPath; + + /** + * 涓婚敭淇℃伅 + */ + @TableField(exist = false) + private GenTableColumn pkColumn; + + /** + * 琛ㄥ垪淇℃伅 + */ + @Valid + @TableField(exist = false) + private List<GenTableColumn> columns; + + /** + * 鍏跺畠鐢熸垚閫夐」 + */ + private String options; + + /** + * 澶囨敞 + */ + private String remark; + + /** + * 鏍戠紪鐮佸瓧娈� + */ + @TableField(exist = false) + private String treeCode; + + /** + * 鏍戠埗缂栫爜瀛楁 + */ + @TableField(exist = false) + private String treeParentCode; + + /** + * 鏍戝悕绉板瓧娈� + */ + @TableField(exist = false) + private String treeName; + + /* + * 鑿滃崟id鍒楄〃 + */ + @TableField(exist = false) + private List<Long> menuIds; + + /** + * 涓婄骇鑿滃崟ID瀛楁 + */ + @TableField(exist = false) + private String parentMenuId; + + /** + * 涓婄骇鑿滃崟鍚嶇О瀛楁 + */ + @TableField(exist = false) + private String parentMenuName; + + public boolean isTree() { + return isTree(this.tplCategory); + } + + public static boolean isTree(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); + } + + public boolean isCrud() { + return isCrud(this.tplCategory); + } + + public static boolean isCrud(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); + } + + public boolean isSuperColumn(String javaField) { + return isSuperColumn(this.tplCategory, javaField); + } + + public static boolean isSuperColumn(String tplCategory, String javaField) { + return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTableColumn.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTableColumn.java new file mode 100644 index 0000000..d2e4611 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/domain/GenTableColumn.java @@ -0,0 +1,222 @@ +package org.ruoyi.generator.domain; + +import com.baomidou.mybatisplus.annotation.FieldStrategy; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import org.ruoyi.common.core.utils.StringUtils; +import org.ruoyi.common.mybatis.core.domain.BaseEntity; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.apache.ibatis.type.JdbcType; + +/** + * 浠g爜鐢熸垚涓氬姟瀛楁琛� gen_table_column + * + * @author Lion Li + */ + +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("gen_table_column") +public class GenTableColumn extends BaseEntity { + + /** + * 缂栧彿 + */ + @TableId(value = "column_id") + private Long columnId; + + /** + * 褰掑睘琛ㄧ紪鍙� + */ + private Long tableId; + + /** + * 鍒楀悕绉� + */ + private String columnName; + + /** + * 鍒楁弿杩� + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String columnComment; + + /** + * 鍒楃被鍨� + */ + private String columnType; + + /** + * JAVA绫诲瀷 + */ + private String javaType; + + /** + * JAVA瀛楁鍚� + */ + @NotBlank(message = "Java灞炴�т笉鑳戒负绌�") + private String javaField; + + /** + * 鏄惁涓婚敭锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isPk; + + /** + * 鏄惁鑷锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isIncrement; + + /** + * 鏄惁蹇呭~锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isRequired; + + /** + * 鏄惁涓烘彃鍏ュ瓧娈碉紙1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isInsert; + + /** + * 鏄惁缂栬緫瀛楁锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isEdit; + + /** + * 鏄惁鍒楄〃瀛楁锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isList; + + /** + * 鏄惁鏌ヨ瀛楁锛�1鏄級 + */ + @TableField(updateStrategy = FieldStrategy.IGNORED, jdbcType = JdbcType.VARCHAR) + private String isQuery; + + /** + * 鏌ヨ鏂瑰紡锛圗Q绛変簬銆丯E涓嶇瓑浜庛�丟T澶т簬銆丩T灏忎簬銆丩IKE妯$硦銆丅ETWEEN鑼冨洿锛� + */ + private String queryType; + + /** + * 鏄剧ず绫诲瀷锛坕nput鏂囨湰妗嗐�乼extarea鏂囨湰鍩熴�乻elect涓嬫媺妗嗐�乧heckbox澶嶉�夋銆乺adio鍗曢�夋銆乨atetime鏃ユ湡鎺т欢銆乮mage鍥剧墖涓婁紶鎺т欢銆乽pload鏂囦欢涓婁紶鎺т欢銆乪ditor瀵屾枃鏈帶浠讹級 + */ + private String htmlType; + + /** + * 瀛楀吀绫诲瀷 + */ + private String dictType; + + /** + * 鎺掑簭 + */ + private Integer sort; + + public String getCapJavaField() { + return StringUtils.capitalize(javaField); + } + + public boolean isPk() { + return isPk(this.isPk); + } + + public boolean isPk(String isPk) { + return isPk != null && StringUtils.equals("1", isPk); + } + + public boolean isIncrement() { + return isIncrement(this.isIncrement); + } + + public boolean isIncrement(String isIncrement) { + return isIncrement != null && StringUtils.equals("1", isIncrement); + } + + public boolean isRequired() { + return isRequired(this.isRequired); + } + + public boolean isRequired(String isRequired) { + return isRequired != null && StringUtils.equals("1", isRequired); + } + + public boolean isInsert() { + return isInsert(this.isInsert); + } + + public boolean isInsert(String isInsert) { + return isInsert != null && StringUtils.equals("1", isInsert); + } + + public boolean isEdit() { + return isInsert(this.isEdit); + } + + public boolean isEdit(String isEdit) { + return isEdit != null && StringUtils.equals("1", isEdit); + } + + public boolean isList() { + return isList(this.isList); + } + + public boolean isList(String isList) { + return isList != null && StringUtils.equals("1", isList); + } + + public boolean isQuery() { + return isQuery(this.isQuery); + } + + public boolean isQuery(String isQuery) { + return isQuery != null && StringUtils.equals("1", isQuery); + } + + public boolean isSuperColumn() { + return isSuperColumn(this.javaField); + } + + public static boolean isSuperColumn(String javaField) { + return StringUtils.equalsAnyIgnoreCase(javaField, + // BaseEntity + "createBy", "createTime", "updateBy", "updateTime", + // TreeEntity + "parentName", "parentId"); + } + + public boolean isUsableColumn() { + return isUsableColumn(javaField); + } + + public static boolean isUsableColumn(String javaField) { + // isSuperColumn()涓殑鍚嶅崟鐢ㄤ簬閬垮厤鐢熸垚澶氫綑Domain灞炴�э紝鑻ユ煇浜涘睘鎬у湪鐢熸垚椤甸潰鏃堕渶瑕佺敤鍒颁笉鑳藉拷鐣ワ紝鍒欐斁鍦ㄦ澶勭櫧鍚嶅崟 + return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark"); + } + + public String readConverterExp() { + String remarks = StringUtils.substringBetween(this.columnComment, "锛�", "锛�"); + StringBuffer sb = new StringBuffer(); + if (StringUtils.isNotEmpty(remarks)) { + for (String value : remarks.split(" ")) { + if (StringUtils.isNotEmpty(value)) { + Object startStr = value.subSequence(0, 1); + String endStr = value.substring(1); + sb.append(StringUtils.EMPTY).append(startStr).append("=").append(endStr).append(StringUtils.SEPARATOR); + } + } + return sb.deleteCharAt(sb.length() - 1).toString(); + } else { + return this.columnComment; + } + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableColumnMapper.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableColumnMapper.java new file mode 100644 index 0000000..888e4cf --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableColumnMapper.java @@ -0,0 +1,24 @@ +package org.ruoyi.generator.mapper; + +import com.baomidou.mybatisplus.annotation.InterceptorIgnore; +import org.ruoyi.generator.domain.GenTableColumn; +import org.ruoyi.common.mybatis.core.mapper.BaseMapperPlus; + +import java.util.List; + +/** + * 涓氬姟瀛楁 鏁版嵁灞� + * + * @author Lion Li + */ +@InterceptorIgnore(dataPermission = "true", tenantLine = "true") +public interface GenTableColumnMapper extends BaseMapperPlus<GenTableColumn, GenTableColumn> { + /** + * 鏍规嵁琛ㄥ悕绉版煡璇㈠垪淇℃伅 + * + * @param tableName 琛ㄥ悕绉� + * @return 鍒椾俊鎭� + */ + List<GenTableColumn> selectDbTableColumnsByName(String tableName); + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableMapper.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableMapper.java new file mode 100644 index 0000000..b03da86 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/mapper/GenTableMapper.java @@ -0,0 +1,58 @@ +package org.ruoyi.generator.mapper; + +import com.baomidou.mybatisplus.annotation.InterceptorIgnore; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.ruoyi.common.mybatis.core.mapper.BaseMapperPlus; +import org.ruoyi.generator.domain.GenTable; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 涓氬姟 鏁版嵁灞� + * + * @author Lion Li + */ +@InterceptorIgnore(dataPermission = "true", tenantLine = "true") +public interface GenTableMapper extends BaseMapperPlus<GenTable, GenTable> { + + /** + * 鏌ヨ鎹簱鍒楄〃 + * + * @param genTable 鏌ヨ鏉′欢 + * @return 鏁版嵁搴撹〃闆嗗悎 + */ + Page<GenTable> selectPageDbTableList(@Param("page") Page<GenTable> page, @Param("genTable") GenTable genTable); + + /** + * 鏌ヨ鎹簱鍒楄〃 + * + * @param tableNames 琛ㄥ悕绉扮粍 + * @return 鏁版嵁搴撹〃闆嗗悎 + */ + List<GenTable> selectDbTableListByNames(String[] tableNames); + + /** + * 鏌ヨ鎵�鏈夎〃淇℃伅 + * + * @return 琛ㄤ俊鎭泦鍚� + */ + List<GenTable> selectGenTableAll(); + + /** + * 鏌ヨ琛↖D涓氬姟淇℃伅 + * + * @param id 涓氬姟ID + * @return 涓氬姟淇℃伅 + */ + GenTable selectGenTableById(Long id); + + /** + * 鏌ヨ琛ㄥ悕绉颁笟鍔′俊鎭� + * + * @param tableName 琛ㄥ悕绉� + * @return 涓氬姟淇℃伅 + */ + GenTable selectGenTableByName(String tableName); + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/GenTableServiceImpl.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/GenTableServiceImpl.java new file mode 100644 index 0000000..6c78597 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/GenTableServiceImpl.java @@ -0,0 +1,459 @@ +package org.ruoyi.generator.service; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.io.IoUtil; +import cn.hutool.core.lang.Dict; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.dynamic.datasource.annotation.DS; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.ruoyi.generator.mapper.GenTableMapper; +import org.ruoyi.common.core.constant.Constants; +import org.ruoyi.common.core.exception.ServiceException; +import org.ruoyi.common.core.utils.StreamUtils; +import org.ruoyi.common.core.utils.StringUtils; +import org.ruoyi.common.core.utils.file.FileUtils; +import org.ruoyi.common.json.utils.JsonUtils; +import org.ruoyi.common.mybatis.core.page.PageQuery; +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +import org.ruoyi.common.satoken.utils.LoginHelper; +import org.ruoyi.generator.constant.GenConstants; +import org.ruoyi.generator.domain.GenTable; +import org.ruoyi.generator.domain.GenTableColumn; +import org.ruoyi.generator.mapper.GenTableColumnMapper; +import org.ruoyi.generator.util.GenUtils; +import org.ruoyi.generator.util.VelocityInitializer; +import org.ruoyi.generator.util.VelocityUtils; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 涓氬姟 鏈嶅姟灞傚疄鐜� + * + * @author Lion Li + */ +@DS("#header.datasource") +@Slf4j +@RequiredArgsConstructor +@Service +public class GenTableServiceImpl implements IGenTableService { + + private final GenTableMapper baseMapper; + private final GenTableColumnMapper genTableColumnMapper; + private final IdentifierGenerator identifierGenerator; + + /** + * 鏌ヨ涓氬姟瀛楁鍒楄〃 + * + * @param tableId 涓氬姟瀛楁缂栧彿 + * @return 涓氬姟瀛楁闆嗗悎 + */ + @Override + public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId) { + return genTableColumnMapper.selectList(new LambdaQueryWrapper<GenTableColumn>() + .eq(GenTableColumn::getTableId, tableId) + .orderByAsc(GenTableColumn::getSort)); + } + + /** + * 鏌ヨ涓氬姟淇℃伅 + * + * @param id 涓氬姟ID + * @return 涓氬姟淇℃伅 + */ + @Override + public GenTable selectGenTableById(Long id) { + GenTable genTable = baseMapper.selectGenTableById(id); + setTableFromOptions(genTable); + return genTable; + } + + @Override + public TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery) { + Page<GenTable> page = baseMapper.selectPage(pageQuery.build(), this.buildGenTableQueryWrapper(genTable)); + return TableDataInfo.build(page); + } + + private QueryWrapper<GenTable> buildGenTableQueryWrapper(GenTable genTable) { + Map<String, Object> params = genTable.getParams(); + QueryWrapper<GenTable> wrapper = Wrappers.query(); + wrapper.like(StringUtils.isNotBlank(genTable.getTableName()), "lower(table_name)", StringUtils.lowerCase(genTable.getTableName())) + .like(StringUtils.isNotBlank(genTable.getTableComment()), "lower(table_comment)", StringUtils.lowerCase(genTable.getTableComment())) + .between(params.get("beginTime") != null && params.get("endTime") != null, + "create_time", params.get("beginTime"), params.get("endTime")); + return wrapper; + } + + + @Override + public TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery) { + Page<GenTable> page = baseMapper.selectPageDbTableList(pageQuery.build(), genTable); + return TableDataInfo.build(page); + } + + /** + * 鏌ヨ鎹簱鍒楄〃 + * + * @param tableNames 琛ㄥ悕绉扮粍 + * @return 鏁版嵁搴撹〃闆嗗悎 + */ + @Override + public List<GenTable> selectDbTableListByNames(String[] tableNames) { + return baseMapper.selectDbTableListByNames(tableNames); + } + + /** + * 鏌ヨ鎵�鏈夎〃淇℃伅 + * + * @return 琛ㄤ俊鎭泦鍚� + */ + @Override + public List<GenTable> selectGenTableAll() { + return baseMapper.selectGenTableAll(); + } + + /** + * 淇敼涓氬姟 + * + * @param genTable 涓氬姟淇℃伅 + * @return 缁撴灉 + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void updateGenTable(GenTable genTable) { + String options = JsonUtils.toJsonString(genTable.getParams()); + genTable.setOptions(options); + int row = baseMapper.updateById(genTable); + if (row > 0) { + for (GenTableColumn cenTableColumn : genTable.getColumns()) { + genTableColumnMapper.updateById(cenTableColumn); + } + } + } + + /** + * 鍒犻櫎涓氬姟瀵硅薄 + * + * @param tableIds 闇�瑕佸垹闄ょ殑鏁版嵁ID + * @return 缁撴灉 + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void deleteGenTableByIds(Long[] tableIds) { + List<Long> ids = Arrays.asList(tableIds); + baseMapper.deleteBatchIds(ids); + genTableColumnMapper.delete(new LambdaQueryWrapper<GenTableColumn>().in(GenTableColumn::getTableId, ids)); + } + + /** + * 瀵煎叆琛ㄧ粨鏋� + * + * @param tableList 瀵煎叆琛ㄥ垪琛� + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void importGenTable(List<GenTable> tableList) { + String operName = LoginHelper.getUsername(); + try { + for (GenTable table : tableList) { + String tableName = table.getTableName(); + GenUtils.initTable(table, operName); + int row = baseMapper.insert(table); + if (row > 0) { + // 淇濆瓨鍒椾俊鎭� + List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); + List<GenTableColumn> saveColumns = new ArrayList<>(); + for (GenTableColumn column : genTableColumns) { + GenUtils.initColumnField(column, table); + saveColumns.add(column); + } + if (CollUtil.isNotEmpty(saveColumns)) { + genTableColumnMapper.insertBatch(saveColumns); + } + } + } + } catch (Exception e) { + throw new ServiceException("瀵煎叆澶辫触锛�" + e.getMessage()); + } + } + + /** + * 棰勮浠g爜 + * + * @param tableId 琛ㄧ紪鍙� + * @return 棰勮鏁版嵁鍒楄〃 + */ + @Override + public Map<String, String> previewCode(Long tableId) { + Map<String, String> dataMap = new LinkedHashMap<>(); + // 鏌ヨ琛ㄤ俊鎭� + GenTable table = baseMapper.selectGenTableById(tableId); + List<Long> menuIds = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + menuIds.add(identifierGenerator.nextId(null).longValue()); + } + table.setMenuIds(menuIds); + // 璁剧疆涓婚敭鍒椾俊鎭� + setPkColumn(table); + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 鑾峰彇妯℃澘鍒楄〃 + List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 娓叉煋妯℃澘 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + dataMap.put(template, sw.toString()); + } + return dataMap; + } + + /** + * 鐢熸垚浠g爜锛堜笅杞芥柟寮忥級 + * + * @param tableName 琛ㄥ悕绉� + * @return 鏁版嵁 + */ + @Override + public byte[] downloadCode(String tableName) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + generatorCode(tableName, zip); + IoUtil.close(zip); + return outputStream.toByteArray(); + } + + /** + * 鐢熸垚浠g爜锛堣嚜瀹氫箟璺緞锛� + * + * @param tableName 琛ㄥ悕绉� + */ + @Override + public void generatorCode(String tableName) { + // 鏌ヨ琛ㄤ俊鎭� + GenTable table = baseMapper.selectGenTableByName(tableName); + // 璁剧疆涓婚敭鍒椾俊鎭� + setPkColumn(table); + + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 鑾峰彇妯℃澘鍒楄〃 + List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + if (!StringUtils.containsAny(template, "sql.vm", "api.ts.vm", "types.ts.vm", "index.vue.vm", "index-tree.vue.vm")) { + // 娓叉煋妯℃澘 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + try { + String path = getGenPath(table, template); + FileUtils.writeUtf8String(sw.toString(), path); + } catch (Exception e) { + throw new ServiceException("娓叉煋妯℃澘澶辫触锛岃〃鍚嶏細" + table.getTableName()); + } + } + } + } + + /** + * 鍚屾鏁版嵁搴� + * + * @param tableName 琛ㄥ悕绉� + */ + @Transactional(rollbackFor = Exception.class) + @Override + public void synchDb(String tableName) { + GenTable table = baseMapper.selectGenTableByName(tableName); + List<GenTableColumn> tableColumns = table.getColumns(); + Map<String, GenTableColumn> tableColumnMap = StreamUtils.toIdentityMap(tableColumns, GenTableColumn::getColumnName); + + List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); + if (CollUtil.isEmpty(dbTableColumns)) { + throw new ServiceException("鍚屾鏁版嵁澶辫触锛屽師琛ㄧ粨鏋勪笉瀛樺湪"); + } + List<String> dbTableColumnNames = StreamUtils.toList(dbTableColumns, GenTableColumn::getColumnName); + + List<GenTableColumn> saveColumns = new ArrayList<>(); + dbTableColumns.forEach(column -> { + GenUtils.initColumnField(column, table); + if (tableColumnMap.containsKey(column.getColumnName())) { + GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName()); + column.setColumnId(prevColumn.getColumnId()); + if (column.isList()) { + // 濡傛灉鏄垪琛紝缁х画淇濈暀鏌ヨ鏂瑰紡/瀛楀吀绫诲瀷閫夐」 + column.setDictType(prevColumn.getDictType()); + column.setQueryType(prevColumn.getQueryType()); + } + if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk() + && (column.isInsert() || column.isEdit()) + && ((column.isUsableColumn()) || (!column.isSuperColumn()))) { + // 濡傛灉鏄�(鏂板/淇敼&闈炰富閿�/闈炲拷鐣ュ強鐖跺睘鎬�)锛岀户缁繚鐣欏繀濉�/鏄剧ず绫诲瀷閫夐」 + column.setIsRequired(prevColumn.getIsRequired()); + column.setHtmlType(prevColumn.getHtmlType()); + } + } + saveColumns.add(column); + }); + if (CollUtil.isNotEmpty(saveColumns)) { + genTableColumnMapper.insertOrUpdateBatch(saveColumns); + } + List<GenTableColumn> delColumns = StreamUtils.filter(tableColumns, column -> !dbTableColumnNames.contains(column.getColumnName())); + if (CollUtil.isNotEmpty(delColumns)) { + List<Long> ids = StreamUtils.toList(delColumns, GenTableColumn::getColumnId); + genTableColumnMapper.deleteBatchIds(ids); + } + } + + /** + * 鎵归噺鐢熸垚浠g爜锛堜笅杞芥柟寮忥級 + * + * @param tableNames 琛ㄦ暟缁� + * @return 鏁版嵁 + */ + @Override + public byte[] downloadCode(String[] tableNames) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + for (String tableName : tableNames) { + generatorCode(tableName, zip); + } + IoUtil.close(zip); + return outputStream.toByteArray(); + } + + /** + * 鏌ヨ琛ㄤ俊鎭苟鐢熸垚浠g爜 + */ + private void generatorCode(String tableName, ZipOutputStream zip) { + // 鏌ヨ琛ㄤ俊鎭� + GenTable table = baseMapper.selectGenTableByName(tableName); + List<Long> menuIds = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + menuIds.add(identifierGenerator.nextId(null).longValue()); + } + table.setMenuIds(menuIds); + // 璁剧疆涓婚敭鍒椾俊鎭� + setPkColumn(table); + + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 鑾峰彇妯℃澘鍒楄〃 + List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 娓叉煋妯℃澘 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + try { + // 娣诲姞鍒皕ip + zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table))); + IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString()); + IoUtil.close(sw); + zip.flush(); + zip.closeEntry(); + } catch (IOException e) { + log.error("娓叉煋妯℃澘澶辫触锛岃〃鍚嶏細" + table.getTableName(), e); + } + } + } + + /** + * 淇敼淇濆瓨鍙傛暟鏍¢獙 + * + * @param genTable 涓氬姟淇℃伅 + */ + @Override + public void validateEdit(GenTable genTable) { + if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) { + String options = JsonUtils.toJsonString(genTable.getParams()); + Dict paramsObj = JsonUtils.parseMap(options); + if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_CODE))) { + throw new ServiceException("鏍戠紪鐮佸瓧娈典笉鑳戒负绌�"); + } else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_PARENT_CODE))) { + throw new ServiceException("鏍戠埗缂栫爜瀛楁涓嶈兘涓虹┖"); + } else if (StringUtils.isEmpty(paramsObj.getStr(GenConstants.TREE_NAME))) { + throw new ServiceException("鏍戝悕绉板瓧娈典笉鑳戒负绌�"); + } + } + } + + /** + * 璁剧疆涓婚敭鍒椾俊鎭� + * + * @param table 涓氬姟琛ㄤ俊鎭� + */ + public void setPkColumn(GenTable table) { + for (GenTableColumn column : table.getColumns()) { + if (column.isPk()) { + table.setPkColumn(column); + break; + } + } + if (ObjectUtil.isNull(table.getPkColumn())) { + table.setPkColumn(table.getColumns().get(0)); + } + + } + + /** + * 璁剧疆浠g爜鐢熸垚鍏朵粬閫夐」鍊� + * + * @param genTable 璁剧疆鍚庣殑鐢熸垚瀵硅薄 + */ + public void setTableFromOptions(GenTable genTable) { + Dict paramsObj = JsonUtils.parseMap(genTable.getOptions()); + if (ObjectUtil.isNotNull(paramsObj)) { + String treeCode = paramsObj.getStr(GenConstants.TREE_CODE); + String treeParentCode = paramsObj.getStr(GenConstants.TREE_PARENT_CODE); + String treeName = paramsObj.getStr(GenConstants.TREE_NAME); + String parentMenuId = paramsObj.getStr(GenConstants.PARENT_MENU_ID); + String parentMenuName = paramsObj.getStr(GenConstants.PARENT_MENU_NAME); + + genTable.setTreeCode(treeCode); + genTable.setTreeParentCode(treeParentCode); + genTable.setTreeName(treeName); + genTable.setParentMenuId(parentMenuId); + genTable.setParentMenuName(parentMenuName); + } + } + + /** + * 鑾峰彇浠g爜鐢熸垚鍦板潃 + * + * @param table 涓氬姟琛ㄤ俊鎭� + * @param template 妯℃澘鏂囦欢璺緞 + * @return 鐢熸垚鍦板潃 + */ + public static String getGenPath(GenTable table, String template) { + String genPath = table.getGenPath(); + if (StringUtils.equals(genPath, "/")) { + return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table); + } + return genPath + File.separator + VelocityUtils.getFileName(template, table); + } +} + diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/IGenTableService.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/IGenTableService.java new file mode 100644 index 0000000..48a0a5e --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/service/IGenTableService.java @@ -0,0 +1,133 @@ +package org.ruoyi.generator.service; + +import org.ruoyi.common.mybatis.core.page.PageQuery; +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +import org.ruoyi.generator.domain.GenTable; +import org.ruoyi.generator.domain.GenTableColumn; + +import java.util.List; +import java.util.Map; + +/** + * 涓氬姟 鏈嶅姟灞� + * + * @author Lion Li + */ +public interface IGenTableService { + + /** + * 鏌ヨ涓氬姟瀛楁鍒楄〃 + * + * @param tableId 涓氬姟瀛楁缂栧彿 + * @return 涓氬姟瀛楁闆嗗悎 + */ + List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId); + + /** + * 鏌ヨ涓氬姟鍒楄〃 + * + * @param genTable 涓氬姟淇℃伅 + * @return 涓氬姟闆嗗悎 + */ + TableDataInfo<GenTable> selectPageGenTableList(GenTable genTable, PageQuery pageQuery); + + /** + * 鏌ヨ鎹簱鍒楄〃 + * + * @param genTable 涓氬姟淇℃伅 + * @return 鏁版嵁搴撹〃闆嗗悎 + */ + TableDataInfo<GenTable> selectPageDbTableList(GenTable genTable, PageQuery pageQuery); + + /** + * 鏌ヨ鎹簱鍒楄〃 + * + * @param tableNames 琛ㄥ悕绉扮粍 + * @return 鏁版嵁搴撹〃闆嗗悎 + */ + List<GenTable> selectDbTableListByNames(String[] tableNames); + + /** + * 鏌ヨ鎵�鏈夎〃淇℃伅 + * + * @return 琛ㄤ俊鎭泦鍚� + */ + List<GenTable> selectGenTableAll(); + + /** + * 鏌ヨ涓氬姟淇℃伅 + * + * @param id 涓氬姟ID + * @return 涓氬姟淇℃伅 + */ + GenTable selectGenTableById(Long id); + + /** + * 淇敼涓氬姟 + * + * @param genTable 涓氬姟淇℃伅 + * @return 缁撴灉 + */ + void updateGenTable(GenTable genTable); + + /** + * 鍒犻櫎涓氬姟淇℃伅 + * + * @param tableIds 闇�瑕佸垹闄ょ殑琛ㄦ暟鎹甀D + * @return 缁撴灉 + */ + void deleteGenTableByIds(Long[] tableIds); + + /** + * 瀵煎叆琛ㄧ粨鏋� + * + * @param tableList 瀵煎叆琛ㄥ垪琛� + */ + void importGenTable(List<GenTable> tableList); + + /** + * 棰勮浠g爜 + * + * @param tableId 琛ㄧ紪鍙� + * @return 棰勮鏁版嵁鍒楄〃 + */ + Map<String, String> previewCode(Long tableId); + + /** + * 鐢熸垚浠g爜锛堜笅杞芥柟寮忥級 + * + * @param tableName 琛ㄥ悕绉� + * @return 鏁版嵁 + */ + byte[] downloadCode(String tableName); + + /** + * 鐢熸垚浠g爜锛堣嚜瀹氫箟璺緞锛� + * + * @param tableName 琛ㄥ悕绉� + * @return 鏁版嵁 + */ + void generatorCode(String tableName); + + /** + * 鍚屾鏁版嵁搴� + * + * @param tableName 琛ㄥ悕绉� + */ + void synchDb(String tableName); + + /** + * 鎵归噺鐢熸垚浠g爜锛堜笅杞芥柟寮忥級 + * + * @param tableNames 琛ㄦ暟缁� + * @return 鏁版嵁 + */ + byte[] downloadCode(String[] tableNames); + + /** + * 淇敼淇濆瓨鍙傛暟鏍¢獙 + * + * @param genTable 涓氬姟淇℃伅 + */ + void validateEdit(GenTable genTable); +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/GenUtils.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/GenUtils.java new file mode 100644 index 0000000..81d3a85 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/GenUtils.java @@ -0,0 +1,233 @@ +package org.ruoyi.generator.util; + +import org.ruoyi.generator.config.GenConfig; +import org.ruoyi.generator.constant.GenConstants; +import org.ruoyi.generator.domain.GenTable; +import org.ruoyi.generator.domain.GenTableColumn; +import org.ruoyi.common.core.utils.StringUtils; +import org.ruoyi.common.satoken.utils.LoginHelper; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.apache.commons.lang3.RegExUtils; + +import java.util.Arrays; + +/** + * 浠g爜鐢熸垚鍣� 宸ュ叿绫� + * + * @author ruoyi + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class GenUtils { + + /** + * 鍒濆鍖栬〃淇℃伅 + */ + public static void initTable(GenTable genTable, String operName) { + genTable.setClassName(convertClassName(genTable.getTableName())); + genTable.setPackageName(GenConfig.getPackageName()); + genTable.setModuleName(getModuleName(GenConfig.getPackageName())); + genTable.setBusinessName(getBusinessName(genTable.getTableName())); + genTable.setFunctionName(replaceText(genTable.getTableComment())); + genTable.setFunctionAuthor(GenConfig.getAuthor()); + genTable.setCreateBy(LoginHelper.getUserId()); + } + + /** + * 鍒濆鍖栧垪灞炴�у瓧娈� + */ + public static void initColumnField(GenTableColumn column, GenTable table) { + String dataType = getDbType(column.getColumnType()); + String columnName = column.getColumnName(); + column.setTableId(table.getTableId()); + column.setCreateBy(table.getCreateBy()); + // 璁剧疆java瀛楁鍚� + column.setJavaField(StringUtils.toCamelCase(columnName)); + // 璁剧疆榛樿绫诲瀷 + column.setJavaType(GenConstants.TYPE_STRING); + column.setQueryType(GenConstants.QUERY_EQ); + + if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType)) { + // 瀛楃涓查暱搴﹁秴杩�500璁剧疆涓烘枃鏈煙 + Integer columnLength = getColumnLength(column.getColumnType()); + String htmlType = columnLength >= 500 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT; + column.setHtmlType(htmlType); + } else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) { + column.setJavaType(GenConstants.TYPE_DATE); + column.setHtmlType(GenConstants.HTML_DATETIME); + } else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) { + column.setHtmlType(GenConstants.HTML_INPUT); + + // 濡傛灉鏄诞鐐瑰瀷 缁熶竴鐢˙igDecimal + String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), StringUtils.SEPARATOR); + if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { + column.setJavaType(GenConstants.TYPE_BIGDECIMAL); + } + // 濡傛灉鏄暣褰� + else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) { + column.setJavaType(GenConstants.TYPE_INTEGER); + } + // 闀挎暣褰� + else { + column.setJavaType(GenConstants.TYPE_LONG); + } + } + + // BO瀵硅薄 榛樿鎻掑叆鍕鹃�� + if (!arraysContains(GenConstants.COLUMNNAME_NOT_ADD, columnName) && !column.isPk()) { + column.setIsInsert(GenConstants.REQUIRE); + } + // BO瀵硅薄 榛樿缂栬緫鍕鹃�� + if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName)) { + column.setIsEdit(GenConstants.REQUIRE); + } + // BO瀵硅薄 榛樿鏄惁蹇呭~鍕鹃�� + if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName)) { + column.setIsRequired(GenConstants.REQUIRE); + } + // VO瀵硅薄 榛樿杩斿洖鍕鹃�� + if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName)) { + column.setIsList(GenConstants.REQUIRE); + } + // BO瀵硅薄 榛樿鏌ヨ鍕鹃�� + if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) { + column.setIsQuery(GenConstants.REQUIRE); + } + + // 鏌ヨ瀛楁绫诲瀷 + if (StringUtils.endsWithIgnoreCase(columnName, "name")) { + column.setQueryType(GenConstants.QUERY_LIKE); + } + // 鐘舵�佸瓧娈佃缃崟閫夋 + if (StringUtils.endsWithIgnoreCase(columnName, "status")) { + column.setHtmlType(GenConstants.HTML_RADIO); + } + // 绫诲瀷&鎬у埆瀛楁璁剧疆涓嬫媺妗� + else if (StringUtils.endsWithIgnoreCase(columnName, "type") + || StringUtils.endsWithIgnoreCase(columnName, "sex")) { + column.setHtmlType(GenConstants.HTML_SELECT); + } + // 鍥剧墖瀛楁璁剧疆鍥剧墖涓婁紶鎺т欢 + else if (StringUtils.endsWithIgnoreCase(columnName, "image")) { + column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD); + } + // 鏂囦欢瀛楁璁剧疆鏂囦欢涓婁紶鎺т欢 + else if (StringUtils.endsWithIgnoreCase(columnName, "file")) { + column.setHtmlType(GenConstants.HTML_FILE_UPLOAD); + } + // 鍐呭瀛楁璁剧疆瀵屾枃鏈帶浠� + else if (StringUtils.endsWithIgnoreCase(columnName, "content")) { + column.setHtmlType(GenConstants.HTML_EDITOR); + } + } + + /** + * 鏍¢獙鏁扮粍鏄惁鍖呭惈鎸囧畾鍊� + * + * @param arr 鏁扮粍 + * @param targetValue 鍊� + * @return 鏄惁鍖呭惈 + */ + public static boolean arraysContains(String[] arr, String targetValue) { + return Arrays.asList(arr).contains(targetValue); + } + + /** + * 鑾峰彇妯″潡鍚� + * + * @param packageName 鍖呭悕 + * @return 妯″潡鍚� + */ + public static String getModuleName(String packageName) { + int lastIndex = packageName.lastIndexOf("."); + int nameLength = packageName.length(); + return StringUtils.substring(packageName, lastIndex + 1, nameLength); + } + + /** + * 鑾峰彇涓氬姟鍚� + * + * @param tableName 琛ㄥ悕 + * @return 涓氬姟鍚� + */ + public static String getBusinessName(String tableName) { + int firstIndex = tableName.indexOf("_"); + int nameLength = tableName.length(); + String businessName = StringUtils.substring(tableName, firstIndex + 1, nameLength); + businessName = StringUtils.toCamelCase(businessName); + return businessName; + } + + /** + * 琛ㄥ悕杞崲鎴怞ava绫诲悕 + * + * @param tableName 琛ㄥ悕绉� + * @return 绫诲悕 + */ + public static String convertClassName(String tableName) { + boolean autoRemovePre = GenConfig.getAutoRemovePre(); + String tablePrefix = GenConfig.getTablePrefix(); + if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) { + String[] searchList = StringUtils.split(tablePrefix, StringUtils.SEPARATOR); + tableName = replaceFirst(tableName, searchList); + } + return StringUtils.convertToCamelCase(tableName); + } + + /** + * 鎵归噺鏇挎崲鍓嶇紑 + * + * @param replacementm 鏇挎崲鍊� + * @param searchList 鏇挎崲鍒楄〃 + * @return + */ + public static String replaceFirst(String replacementm, String[] searchList) { + String text = replacementm; + for (String searchString : searchList) { + if (replacementm.startsWith(searchString)) { + text = replacementm.replaceFirst(searchString, ""); + break; + } + } + return text; + } + + /** + * 鍏抽敭瀛楁浛鎹� + * + * @param text 闇�瑕佽鏇挎崲鐨勫悕瀛� + * @return 鏇挎崲鍚庣殑鍚嶅瓧 + */ + public static String replaceText(String text) { + return RegExUtils.replaceAll(text, "(?:琛▅鑻ヤ緷)", ""); + } + + /** + * 鑾峰彇鏁版嵁搴撶被鍨嬪瓧娈� + * + * @param columnType 鍒楃被鍨� + * @return 鎴彇鍚庣殑鍒楃被鍨� + */ + public static String getDbType(String columnType) { + if (StringUtils.indexOf(columnType, '(') > 0) { + return StringUtils.substringBefore(columnType, "("); + } else { + return columnType; + } + } + + /** + * 鑾峰彇瀛楁闀垮害 + * + * @param columnType 鍒楃被鍨� + * @return 鎴彇鍚庣殑鍒楃被鍨� + */ + public static Integer getColumnLength(String columnType) { + if (StringUtils.indexOf(columnType, '(') > 0) { + String length = StringUtils.substringBetween(columnType, "(", ")"); + return Integer.valueOf(length); + } else { + return 0; + } + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityInitializer.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityInitializer.java new file mode 100644 index 0000000..8a94f40 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityInitializer.java @@ -0,0 +1,35 @@ +package org.ruoyi.generator.util; + +import org.ruoyi.common.core.constant.Constants; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.apache.velocity.app.Velocity; + +import java.util.Properties; + +/** + * VelocityEngine宸ュ巶 + * + * @author ruoyi + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class VelocityInitializer { + + /** + * 鍒濆鍖杤m鏂规硶 + */ + public static void initVelocity() { + Properties p = new Properties(); + try { + // 鍔犺浇classpath鐩綍涓嬬殑vm鏂囦欢 + p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + // 瀹氫箟瀛楃闆� + p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8); + // 鍒濆鍖朧elocity寮曟搸锛屾寚瀹氶厤缃甈roperties + Velocity.init(p); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityUtils.java b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityUtils.java new file mode 100644 index 0000000..1742348 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/java/org/ruoyi/generator/util/VelocityUtils.java @@ -0,0 +1,338 @@ +package org.ruoyi.generator.util; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.convert.Convert; +import cn.hutool.core.lang.Dict; +import org.ruoyi.generator.constant.GenConstants; +import org.ruoyi.generator.domain.GenTable; +import org.ruoyi.generator.domain.GenTableColumn; +import org.ruoyi.common.core.utils.DateUtils; +import org.ruoyi.common.core.utils.StringUtils; +import org.ruoyi.common.json.utils.JsonUtils; +import org.ruoyi.common.mybatis.helper.DataBaseHelper; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import org.apache.velocity.VelocityContext; + +import java.util.*; + +/** + * 妯℃澘澶勭悊宸ュ叿绫� + * + * @author ruoyi + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class VelocityUtils { + + /** + * 椤圭洰绌洪棿璺緞 + */ + private static final String PROJECT_PATH = "main/java"; + + /** + * mybatis绌洪棿璺緞 + */ + private static final String MYBATIS_PATH = "main/resources/mapper"; + + /** + * 榛樿涓婄骇鑿滃崟锛岀郴缁熷伐鍏� + */ + private static final String DEFAULT_PARENT_MENU_ID = "3"; + + /** + * 璁剧疆妯℃澘鍙橀噺淇℃伅 + * + * @return 妯℃澘鍒楄〃 + */ + public static VelocityContext prepareContext(GenTable genTable) { + String moduleName = genTable.getModuleName(); + String businessName = genTable.getBusinessName(); + String packageName = genTable.getPackageName(); + String tplCategory = genTable.getTplCategory(); + String functionName = genTable.getFunctionName(); + + VelocityContext velocityContext = new VelocityContext(); + velocityContext.put("tplCategory", genTable.getTplCategory()); + velocityContext.put("tableName", genTable.getTableName()); + velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "銆愯濉啓鍔熻兘鍚嶇О銆�"); + velocityContext.put("ClassName", genTable.getClassName()); + velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); + velocityContext.put("moduleName", genTable.getModuleName()); + velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName())); + velocityContext.put("businessName", genTable.getBusinessName()); + velocityContext.put("basePackage", getPackagePrefix(packageName)); + velocityContext.put("packageName", packageName); + velocityContext.put("author", genTable.getFunctionAuthor()); + velocityContext.put("datetime", DateUtils.getDate()); + velocityContext.put("pkColumn", genTable.getPkColumn()); + velocityContext.put("importList", getImportList(genTable)); + velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); + velocityContext.put("columns", genTable.getColumns()); + velocityContext.put("table", genTable); + velocityContext.put("dicts", getDicts(genTable)); + setMenuVelocityContext(velocityContext, genTable); + if (GenConstants.TPL_TREE.equals(tplCategory)) { + setTreeVelocityContext(velocityContext, genTable); + } + return velocityContext; + } + + public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { + String options = genTable.getOptions(); + Dict paramsObj = JsonUtils.parseMap(options); + String parentMenuId = getParentMenuId(paramsObj); + context.put("parentMenuId", parentMenuId); + } + + public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) { + String options = genTable.getOptions(); + Dict paramsObj = JsonUtils.parseMap(options); + String treeCode = getTreecode(paramsObj); + String treeParentCode = getTreeParentCode(paramsObj); + String treeName = getTreeName(paramsObj); + + context.put("treeCode", treeCode); + context.put("treeParentCode", treeParentCode); + context.put("treeName", treeName); + context.put("expandColumn", getExpandColumn(genTable)); + if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { + context.put("tree_parent_code", paramsObj.get(GenConstants.TREE_PARENT_CODE)); + } + if (paramsObj.containsKey(GenConstants.TREE_NAME)) { + context.put("tree_name", paramsObj.get(GenConstants.TREE_NAME)); + } + } + + /** + * 鑾峰彇妯℃澘淇℃伅 + * + * @return 妯℃澘鍒楄〃 + */ + public static List<String> getTemplateList(String tplCategory) { + List<String> templates = new ArrayList<String>(); + templates.add("vm/java/domain.java.vm"); + templates.add("vm/java/vo.java.vm"); + templates.add("vm/java/bo.java.vm"); + templates.add("vm/java/mapper.java.vm"); + templates.add("vm/java/service.java.vm"); + templates.add("vm/java/serviceImpl.java.vm"); + templates.add("vm/java/controller.java.vm"); + templates.add("vm/xml/mapper.xml.vm"); + if (DataBaseHelper.isOracle()) { + templates.add("vm/sql/oracle/sql.vm"); + } else if (DataBaseHelper.isPostgerSql()) { + templates.add("vm/sql/postgres/sql.vm"); + } else if (DataBaseHelper.isSqlServer()) { + templates.add("vm/sql/sqlserver/sql.vm"); + } else { + templates.add("vm/sql/sql.vm"); + } + templates.add("vm/ts/api.ts.vm"); + templates.add("vm/ts/types.ts.vm"); + if (GenConstants.TPL_CRUD.equals(tplCategory)) { + templates.add("vm/vue/index.vue.vm"); + } else if (GenConstants.TPL_TREE.equals(tplCategory)) { + templates.add("vm/vue/index-tree.vue.vm"); + } + return templates; + } + + /** + * 鑾峰彇鏂囦欢鍚� + */ + public static String getFileName(String template, GenTable genTable) { + // 鏂囦欢鍚嶇О + String fileName = ""; + // 鍖呰矾寰� + String packageName = genTable.getPackageName(); + // 妯″潡鍚� + String moduleName = genTable.getModuleName(); + // 澶у啓绫诲悕 + String className = genTable.getClassName(); + // 涓氬姟鍚嶇О + String businessName = genTable.getBusinessName(); + + String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); + String mybatisPath = MYBATIS_PATH + "/" + moduleName; + String vuePath = "vue"; + + if (template.contains("domain.java.vm")) { + fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); + } + if (template.contains("vo.java.vm")) { + fileName = StringUtils.format("{}/domain/vo/{}Vo.java", javaPath, className); + } + if (template.contains("bo.java.vm")) { + fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className); + } + if (template.contains("mapper.java.vm")) { + fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); + } else if (template.contains("service.java.vm")) { + fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); + } else if (template.contains("serviceImpl.java.vm")) { + fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); + } else if (template.contains("controller.java.vm")) { + fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); + } else if (template.contains("mapper.xml.vm")) { + fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); + } else if (template.contains("sql.vm")) { + fileName = businessName + "Menu.sql"; + } else if (template.contains("api.ts.vm")) { + fileName = StringUtils.format("{}/api/{}/{}/index.ts", vuePath, moduleName, businessName); + } else if (template.contains("types.ts.vm")) { + fileName = StringUtils.format("{}/api/{}/{}/types.ts", vuePath, moduleName, businessName); + } else if (template.contains("index.vue.vm")) { + fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + } else if (template.contains("index-tree.vue.vm")) { + fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + } + return fileName; + } + + /** + * 鑾峰彇鍖呭墠缂� + * + * @param packageName 鍖呭悕绉� + * @return 鍖呭墠缂�鍚嶇О + */ + public static String getPackagePrefix(String packageName) { + int lastIndex = packageName.lastIndexOf("."); + return StringUtils.substring(packageName, 0, lastIndex); + } + + /** + * 鏍规嵁鍒楃被鍨嬭幏鍙栧鍏ュ寘 + * + * @param genTable 涓氬姟琛ㄥ璞� + * @return 杩斿洖闇�瑕佸鍏ョ殑鍖呭垪琛� + */ + public static HashSet<String> getImportList(GenTable genTable) { + List<GenTableColumn> columns = genTable.getColumns(); + HashSet<String> importList = new HashSet<String>(); + for (GenTableColumn column : columns) { + if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) { + importList.add("java.util.Date"); + importList.add("com.fasterxml.jackson.annotation.JsonFormat"); + } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) { + importList.add("java.math.BigDecimal"); + } + } + return importList; + } + + /** + * 鏍规嵁鍒楃被鍨嬭幏鍙栧瓧鍏哥粍 + * + * @param genTable 涓氬姟琛ㄥ璞� + * @return 杩斿洖瀛楀吀缁� + */ + public static String getDicts(GenTable genTable) { + List<GenTableColumn> columns = genTable.getColumns(); + Set<String> dicts = new HashSet<>(); + addDicts(dicts, columns); + return StringUtils.join(dicts, ", "); + } + + /** + * 娣诲姞瀛楀吀鍒楄〃 + * + * @param dicts 瀛楀吀鍒楄〃 + * @param columns 鍒楅泦鍚� + */ + public static void addDicts(Set<String> dicts, List<GenTableColumn> columns) { + for (GenTableColumn column : columns) { + if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny( + column.getHtmlType(), + new String[] { GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX })) { + dicts.add("'" + column.getDictType() + "'"); + } + } + } + + /** + * 鑾峰彇鏉冮檺鍓嶇紑 + * + * @param moduleName 妯″潡鍚嶇О + * @param businessName 涓氬姟鍚嶇О + * @return 杩斿洖鏉冮檺鍓嶇紑 + */ + public static String getPermissionPrefix(String moduleName, String businessName) { + return StringUtils.format("{}:{}", moduleName, businessName); + } + + /** + * 鑾峰彇涓婄骇鑿滃崟ID瀛楁 + * + * @param paramsObj 鐢熸垚鍏朵粬閫夐」 + * @return 涓婄骇鑿滃崟ID瀛楁 + */ + public static String getParentMenuId(Dict paramsObj) { + if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID) + && StringUtils.isNotEmpty(paramsObj.getStr(GenConstants.PARENT_MENU_ID))) { + return paramsObj.getStr(GenConstants.PARENT_MENU_ID); + } + return DEFAULT_PARENT_MENU_ID; + } + + /** + * 鑾峰彇鏍戠紪鐮� + * + * @param paramsObj 鐢熸垚鍏朵粬閫夐」 + * @return 鏍戠紪鐮� + */ + public static String getTreecode(Map<String, Object> paramsObj) { + if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_CODE)) { + return StringUtils.toCamelCase(Convert.toStr(paramsObj.get(GenConstants.TREE_CODE))); + } + return StringUtils.EMPTY; + } + + /** + * 鑾峰彇鏍戠埗缂栫爜 + * + * @param paramsObj 鐢熸垚鍏朵粬閫夐」 + * @return 鏍戠埗缂栫爜 + */ + public static String getTreeParentCode(Dict paramsObj) { + if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { + return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_PARENT_CODE)); + } + return StringUtils.EMPTY; + } + + /** + * 鑾峰彇鏍戝悕绉� + * + * @param paramsObj 鐢熸垚鍏朵粬閫夐」 + * @return 鏍戝悕绉� + */ + public static String getTreeName(Dict paramsObj) { + if (CollUtil.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.TREE_NAME)) { + return StringUtils.toCamelCase(paramsObj.getStr(GenConstants.TREE_NAME)); + } + return StringUtils.EMPTY; + } + + /** + * 鑾峰彇闇�瑕佸湪鍝竴鍒椾笂闈㈡樉绀哄睍寮�鎸夐挳 + * + * @param genTable 涓氬姟琛ㄥ璞� + * @return 灞曞紑鎸夐挳鍒楀簭鍙� + */ + public static int getExpandColumn(GenTable genTable) { + String options = genTable.getOptions(); + Dict paramsObj = JsonUtils.parseMap(options); + String treeName = paramsObj.getStr(GenConstants.TREE_NAME); + int num = 0; + for (GenTableColumn column : genTable.getColumns()) { + if (column.isList()) { + num++; + String columnName = column.getColumnName(); + if (columnName.equals(treeName)) { + break; + } + } + } + return num; + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/generator.yml b/ruoyi-modules/ruoyi-generator/src/main/resources/generator.yml new file mode 100644 index 0000000..fea39ec --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/generator.yml @@ -0,0 +1,10 @@ +# 浠g爜鐢熸垚 +gen: + # 浣滆�� + author: ageerle + # 榛樿鐢熸垚鍖呰矾寰� system 闇�鏀规垚鑷繁鐨勬ā鍧楀悕绉� 濡� system monitor tool + packageName: org.ruoyi.system + # 鑷姩鍘婚櫎琛ㄥ墠缂�锛岄粯璁ゆ槸false + autoRemovePre: false + # 琛ㄥ墠缂�锛堢敓鎴愮被鍚嶄笉浼氬寘鍚〃鍓嶇紑锛屽涓敤閫楀彿鍒嗛殧锛� + tablePrefix: sys_ diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml new file mode 100644 index 0000000..3dfd97c --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml @@ -0,0 +1,93 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<mapper namespace="org.ruoyi.generator.mapper.GenTableColumnMapper"> + + <resultMap type="org.ruoyi.generator.domain.GenTableColumn" id="GenTableColumnResult"> + </resultMap> + + <select id="selectDbTableColumnsByName" parameterType="String" resultMap="GenTableColumnResult"> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isMySql()"> + select column_name, + (case when (is_nullable = 'no' <![CDATA[ && ]]> column_key != 'PRI') then '1' else null end) as is_required, + (case when column_key = 'PRI' then '1' else '0' end) as is_pk, + ordinal_position as sort, + column_comment, + (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, + column_type + from information_schema.columns where table_schema = (select database()) and table_name = (#{tableName}) + order by ordinal_position + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isOracle()"> + select lower(temp.column_name) as column_name, + (case when (temp.nullable = 'N' and temp.constraint_type != 'P') then '1' else null end) as is_required, + (case when temp.constraint_type = 'P' then '1' else '0' end) as is_pk, + temp.column_id as sort, + temp.comments as column_comment, + (case when temp.constraint_type = 'P' then '1' else '0' end) as is_increment, + lower(temp.data_type) as column_type + from ( + select col.column_id, col.column_name,col.nullable, col.data_type, colc.comments, uc.constraint_type, row_number() + over (partition by col.column_name order by uc.constraint_type desc) as row_flg + from user_tab_columns col + left join user_col_comments colc on colc.table_name = col.table_name and colc.column_name = col.column_name + left join user_cons_columns ucc on ucc.table_name = col.table_name and ucc.column_name = col.column_name + left join user_constraints uc on uc.constraint_name = ucc.constraint_name + where col.table_name = upper(#{tableName}) + ) temp + WHERE temp.row_flg = 1 + ORDER BY temp.column_id + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isPostgerSql()"> + SELECT column_name, is_required, is_pk, sort, column_comment, is_increment, column_type + FROM ( + SELECT c.relname AS table_name, + a.attname AS column_name, + d.description AS column_comment, + CASE WHEN a.attnotnull AND con.conname IS NULL THEN 1 ELSE 0 + END AS is_required, + CASE WHEN con.conname IS NOT NULL THEN 1 ELSE 0 + END AS is_pk, + a.attnum AS sort, + CASE WHEN "position"(pg_get_expr(ad.adbin, ad.adrelid), + ((c.relname::text || '_'::text) || a.attname::text) || '_seq'::text) > 0 THEN 1 ELSE 0 + END AS is_increment, + btrim( + CASE WHEN t.typelem <![CDATA[ <> ]]> 0::oid AND t.typlen = '-1'::integer THEN 'ARRAY'::text ELSE + CASE WHEN t.typtype = 'd'::"char" THEN format_type(t.typbasetype, NULL::integer) + ELSE format_type(a.atttypid, NULL::integer) END + END, '"'::text + ) AS column_type + FROM pg_attribute a + JOIN (pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid) ON a.attrelid = c.oid + LEFT JOIN pg_description d ON d.objoid = c.oid AND a.attnum = d.objsubid + LEFT JOIN pg_constraint con ON con.conrelid = c.oid AND (a.attnum = ANY (con.conkey)) + LEFT JOIN pg_attrdef ad ON a.attrelid = ad.adrelid AND a.attnum = ad.adnum + LEFT JOIN pg_type t ON a.atttypid = t.oid + WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"])) + AND a.attnum > 0 + AND n.nspname = 'public'::name + ORDER BY c.relname, a.attnum + ) temp + WHERE table_name = (#{tableName}) + AND column_type <![CDATA[ <> ]]> '-' + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isSqlServer()"> + SELECT + cast(A.NAME as nvarchar) as column_name, + cast(B.NAME as nvarchar) + (case when B.NAME = 'numeric' then '(' + cast(A.prec as nvarchar) + ',' + cast(A.scale as nvarchar) + ')' else '' end) as column_type, + cast(G.[VALUE] as nvarchar) as column_comment, + (SELECT 1 FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE Z WHERE TABLE_NAME = D.NAME and A.NAME = Z.column_name ) as is_pk, + colorder as sort + FROM SYSCOLUMNS A + LEFT JOIN SYSTYPES B ON A.XTYPE = B.XUSERTYPE + INNER JOIN SYSOBJECTS D ON A.ID = D.ID AND D.XTYPE='U' AND D.NAME != 'DTPROPERTIES' + LEFT JOIN SYS.EXTENDED_PROPERTIES G ON A.ID = G.MAJOR_ID AND A.COLID = G.MINOR_ID + LEFT JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID AND F.MINOR_ID = 0 + WHERE D.NAME = #{tableName} + ORDER BY A.COLORDER + </if> + </select> + +</mapper> diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml new file mode 100644 index 0000000..a0a7695 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/generator/GenTableMapper.xml @@ -0,0 +1,220 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<mapper namespace="org.ruoyi.generator.mapper.GenTableMapper"> + + <!-- 澶氱粨鏋勫祵濂楄嚜鍔ㄦ槧灏勯渶甯︿笂姣忎釜瀹炰綋鐨勪富閿甶d 鍚﹀垯鏄犲皠浼氬け璐� --> + <resultMap type="org.ruoyi.generator.domain.GenTable" id="GenTableResult"> + <id property="tableId" column="table_id" /> + <collection property="columns" javaType="java.util.List" resultMap="GenTableColumnResult" /> + </resultMap> + + <resultMap type="org.ruoyi.generator.domain.GenTableColumn" id="GenTableColumnResult"> + <id property="columnId" column="column_id"/> + </resultMap> + + <select id="selectPageDbTableList" resultMap="GenTableResult"> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isMySql()"> + select table_name, table_comment, create_time, update_time + from information_schema.tables + where table_schema = (select database()) + AND table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%' + AND table_name NOT IN (select table_name from gen_table) + <if test="genTable.tableName != null and genTable.tableName != ''"> + AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%')) + </if> + <if test="genTable.tableComment != null and genTable.tableComment != ''"> + AND lower(table_comment) like lower(concat('%', #{genTable.tableComment}, '%')) + </if> + order by create_time desc + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isOracle()"> + select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time + from user_tables dt, user_tab_comments dtc, user_objects uo + where dt.table_name = dtc.table_name + and dt.table_name = uo.object_name + and uo.object_type = 'TABLE' + AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%' + AND lower(dt.table_name) NOT IN (select table_name from gen_table) + <if test="genTable.tableName != null and genTable.tableName != ''"> + AND lower(dt.table_name) like lower(concat(concat('%', #{genTable.tableName}), '%')) + </if> + <if test="genTable.tableComment != null and genTable.tableComment != ''"> + AND lower(dtc.comments) like lower(concat(concat('%', #{genTable.tableComment}), '%')) + </if> + order by create_time desc + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isPostgerSql()"> + select table_name, table_comment, create_time, update_time + from ( + SELECT c.relname AS table_name, + obj_description(c.oid) AS table_comment, + CURRENT_TIMESTAMP AS create_time, + CURRENT_TIMESTAMP AS update_time + FROM pg_class c + LEFT JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"])) + AND c.relname != 'spatial_%'::text + AND n.nspname = 'public'::name + AND n.nspname <![CDATA[ <> ]]> ''::name + ) list_table + where table_name NOT LIKE 'xxl_job_%' AND table_name NOT LIKE 'gen_%' + AND table_name NOT IN (select table_name from gen_table) + <if test="genTable.tableName != null and genTable.tableName != ''"> + AND lower(table_name) like lower(concat('%', #{genTable.tableName}, '%')) + </if> + <if test="genTable.tableComment != null and genTable.tableComment != ''"> + AND lower(table_comment) like lower(concat('%', #{genTable.tableComment}, '%')) + </if> + order by create_time desc + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isSqlServer()"> + SELECT cast(D.NAME as nvarchar) as table_name, + cast(F.VALUE as nvarchar) as table_comment, + crdate as create_time, + refdate as update_time + FROM SYSOBJECTS D + INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID + AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES' + AND D.NAME NOT LIKE 'xxl_job_%' AND D.NAME NOT LIKE 'gen_%' + AND D.NAME NOT IN (select table_name from gen_table) + <if test="genTable.tableName != null and genTable.tableName != ''"> + AND lower(D.NAME) like lower(concat(N'%', N'${genTable.tableName}', N'%')) + </if> + <if test="genTable.tableComment != null and genTable.tableComment != ''"> + AND lower(CAST(F.VALUE AS nvarchar)) like lower(concat(N'%', N'${genTable.tableComment}', N'%')) + </if> + order by crdate desc + </if> + </select> + + <select id="selectDbTableListByNames" resultMap="GenTableResult"> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isMySql()"> + select table_name, table_comment, create_time, update_time from information_schema.tables + where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database()) + and table_name in + <foreach collection="array" item="name" open="(" separator="," close=")"> + #{name} + </foreach> + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isOracle()"> + select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time + from user_tables dt, user_tab_comments dtc, user_objects uo + where dt.table_name = dtc.table_name + and dt.table_name = uo.object_name + and uo.object_type = 'TABLE' + AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%' + AND dt.table_name NOT IN (select table_name from gen_table) + and lower(dt.table_name) in + <foreach collection="array" item="name" open="(" separator="," close=")"> + #{name} + </foreach> + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isPostgerSql()"> + select table_name, table_comment, create_time, update_time + from ( + SELECT c.relname AS table_name, + obj_description(c.oid) AS table_comment, + CURRENT_TIMESTAMP AS create_time, + CURRENT_TIMESTAMP AS update_time + FROM pg_class c + LEFT JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"])) + AND c.relname != 'spatial_%'::text + AND n.nspname = 'public'::name + AND n.nspname <![CDATA[ <> ]]> ''::name + ) list_table + where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' + and table_name in + <foreach collection="array" item="name" open="(" separator="," close=")"> + #{name} + </foreach> + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isSqlServer()"> + SELECT cast(D.NAME as nvarchar) as table_name, + cast(F.VALUE as nvarchar) as table_comment, + crdate as create_time, + refdate as update_time + FROM SYSOBJECTS D + INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID + AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES' + AND D.NAME NOT LIKE 'xxl_job_%' AND D.NAME NOT LIKE 'gen_%' + AND D.NAME in + <foreach collection="array" item="name" open="(" separator="," close=")"> + #{name} + </foreach> + </if> + </select> + + <select id="selectTableByName" parameterType="String" resultMap="GenTableResult"> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isMySql()"> + select table_name, table_comment, create_time, update_time from information_schema.tables + where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' and table_schema = (select database()) + and table_name = #{tableName} + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isOracle()"> + select lower(dt.table_name) as table_name, dtc.comments as table_comment, uo.created as create_time, uo.last_ddl_time as update_time + from user_tables dt, user_tab_comments dtc, user_objects uo + where dt.table_name = dtc.table_name + and dt.table_name = uo.object_name + and uo.object_type = 'TABLE' + AND dt.table_name NOT LIKE 'XXL_JOB_%' AND dt.table_name NOT LIKE 'GEN_%' + AND dt.table_name NOT IN (select table_name from gen_table) + and lower(dt.table_name) = #{tableName} + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isPostgerSql()"> + select table_name, table_comment, create_time, update_time + from ( + SELECT c.relname AS table_name, + obj_description(c.oid) AS table_comment, + CURRENT_TIMESTAMP AS create_time, + CURRENT_TIMESTAMP AS update_time + FROM pg_class c + LEFT JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE (c.relkind = ANY (ARRAY ['r'::"char", 'p'::"char"])) + AND c.relname != 'spatial_%'::text + AND n.nspname = 'public'::name + AND n.nspname <![CDATA[ <> ]]> ''::name + ) list_table + where table_name NOT LIKE 'xxl_job_%' and table_name NOT LIKE 'gen_%' + and table_name = #{tableName} + </if> + <if test="@org.ruoyi.common.mybatis.helper.DataBaseHelper@isSqlServer()"> + SELECT cast(D.NAME as nvarchar) as table_name, + cast(F.VALUE as nvarchar) as table_comment, + crdate as create_time, + refdate as update_time + FROM SYSOBJECTS D + INNER JOIN SYS.EXTENDED_PROPERTIES F ON D.ID = F.MAJOR_ID + AND F.MINOR_ID = 0 AND D.XTYPE = 'U' AND D.NAME != 'DTPROPERTIES' + AND D.NAME NOT LIKE 'xxl_job_%' AND D.NAME NOT LIKE 'gen_%' + AND D.NAME = #{tableName} + </if> + </select> + + <select id="selectGenTableById" parameterType="Long" resultMap="GenTableResult"> + SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark, + c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort + FROM gen_table t + LEFT JOIN gen_table_column c ON t.table_id = c.table_id + where t.table_id = #{tableId} order by c.sort + </select> + + <select id="selectGenTableByName" parameterType="String" resultMap="GenTableResult"> + SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.gen_type, t.gen_path, t.options, t.remark, + c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort + FROM gen_table t + LEFT JOIN gen_table_column c ON t.table_id = c.table_id + where t.table_name = #{tableName} order by c.sort + </select> + + <select id="selectGenTableAll" parameterType="String" resultMap="GenTableResult"> + SELECT t.table_id, t.table_name, t.table_comment, t.sub_table_name, t.sub_table_fk_name, t.class_name, t.tpl_category, t.package_name, t.module_name, t.business_name, t.function_name, t.function_author, t.options, t.remark, + c.column_id, c.column_name, c.column_comment, c.column_type, c.java_type, c.java_field, c.is_pk, c.is_increment, c.is_required, c.is_insert, c.is_edit, c.is_list, c.is_query, c.query_type, c.html_type, c.dict_type, c.sort + FROM gen_table t + LEFT JOIN gen_table_column c ON t.table_id = c.table_id + order by c.sort + </select> + +</mapper> diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/package-info.md b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/package-info.md new file mode 100644 index 0000000..c938b1e --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/mapper/package-info.md @@ -0,0 +1,3 @@ +java鍖呬娇鐢� `.` 鍒嗗壊 resource 鐩綍浣跨敤 `/` 鍒嗗壊 +<br> +姝ゆ枃浠剁洰鐨� 闃叉鏂囦欢澶圭矘杩炴壘涓嶅埌 `xml` 鏂囦欢 \ No newline at end of file diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/bo.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/bo.java.vm new file mode 100644 index 0000000..21f32f0 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/bo.java.vm @@ -0,0 +1,48 @@ +package ${packageName}.domain.bo; + +import ${packageName}.domain.${ClassName}; +import org.ruoyi.common.mybatis.core.domain.BaseEntity; +import io.github.linpeilie.annotations.AutoMapper; +import lombok.Data; +import lombok.EqualsAndHashCode; +import jakarta.validation.constraints.*; +#foreach ($import in $importList) +import ${import}; +#end + +/** + * ${functionName}涓氬姟瀵硅薄 ${tableName} + * + * @author ${author} + * @date ${datetime} + */ +@Data +@EqualsAndHashCode(callSuper = true) +@AutoMapper(target = ${ClassName}.class, reverseConvertGenerate = false) +public class ${ClassName}Bo extends BaseEntity { + +#foreach ($column in $columns) +#if(!$table.isSuperColumn($column.javaField) && ($column.query || $column.insert || $column.edit)) + /** + * $column.columnComment + */ +#if($column.insert && $column.edit) +#set($Group="AddGroup.class, EditGroup.class") +#elseif($column.insert) +#set($Group="AddGroup.class") +#elseif($column.edit) +#set($Group="EditGroup.class") +#end +#if($column.required) +#if($column.javaType == 'String') + @NotBlank(message = "$column.columnComment涓嶈兘涓虹┖", groups = { $Group }) +#else + @NotNull(message = "$column.columnComment涓嶈兘涓虹┖", groups = { $Group }) +#end +#end + private $column.javaType $column.javaField; + +#end +#end + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/controller.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/controller.java.vm new file mode 100644 index 0000000..25ab0b3 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/controller.java.vm @@ -0,0 +1,115 @@ +package ${packageName}.controller; + +import java.util.List; + +import lombok.RequiredArgsConstructor; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.validation.constraints.*; +import cn.dev33.satoken.annotation.SaCheckPermission; +import org.springframework.web.bind.annotation.*; +import org.springframework.validation.annotation.Validated; +import annotation.idempotent.common.org.ruoyi.RepeatSubmit; +import org.ruoyi.common.log.annotation.Log; +import org.ruoyi.common.web.core.BaseController; +import org.ruoyi.common.mybatis.core.page.PageQuery; +import org.ruoyi.common.core.domain.R; +import org.ruoyi.common.core.validate.AddGroup; +import org.ruoyi.common.core.validate.EditGroup; +import org.ruoyi.common.log.enums.BusinessType; +import utils.excel.common.org.ruoyi.ExcelUtil; +import ${packageName}.domain.vo.${ClassName}Vo; +import ${packageName}.domain.bo.${ClassName}Bo; +import ${packageName}.service.I${ClassName}Service; +#if($table.crud || $table.sub) +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +#elseif($table.tree) +#end + +/** + * ${functionName} + * + * @author ${author} + * @date ${datetime} + */ +@Validated +@RequiredArgsConstructor +@RestController +@RequestMapping("/${moduleName}/${businessName}") +public class ${ClassName}Controller extends BaseController { + + private final I${ClassName}Service ${className}Service; + + /** + * 鏌ヨ${functionName}鍒楄〃 + */ + @SaCheckPermission("${permissionPrefix}:list") + @GetMapping("/list") +#if($table.crud || $table.sub) + public TableDataInfo<${ClassName}Vo> list(${ClassName}Bo bo, PageQuery pageQuery) { + return ${className}Service.queryPageList(bo, pageQuery); + } +#elseif($table.tree) + public R<List<${ClassName}Vo>> list(${ClassName}Bo bo) { + List<${ClassName}Vo> list = ${className}Service.queryList(bo); + return R.ok(list); + } +#end + + /** + * 瀵煎嚭${functionName}鍒楄〃 + */ + @SaCheckPermission("${permissionPrefix}:export") + @Log(title = "${functionName}", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(${ClassName}Bo bo, HttpServletResponse response) { + List<${ClassName}Vo> list = ${className}Service.queryList(bo); + ExcelUtil.exportExcel(list, "${functionName}", ${ClassName}Vo.class, response); + } + + /** + * 鑾峰彇${functionName}璇︾粏淇℃伅 + * + * @param ${pkColumn.javaField} 涓婚敭 + */ + @SaCheckPermission("${permissionPrefix}:query") + @GetMapping("/{${pkColumn.javaField}}") + public R<${ClassName}Vo> getInfo(@NotNull(message = "涓婚敭涓嶈兘涓虹┖") + @PathVariable ${pkColumn.javaType} ${pkColumn.javaField}) { + return R.ok(${className}Service.queryById(${pkColumn.javaField})); + } + + /** + * 鏂板${functionName} + */ + @SaCheckPermission("${permissionPrefix}:add") + @Log(title = "${functionName}", businessType = BusinessType.INSERT) + @RepeatSubmit() + @PostMapping() + public R<Void> add(@Validated(AddGroup.class) @RequestBody ${ClassName}Bo bo) { + return toAjax(${className}Service.insertByBo(bo)); + } + + /** + * 淇敼${functionName} + */ + @SaCheckPermission("${permissionPrefix}:edit") + @Log(title = "${functionName}", businessType = BusinessType.UPDATE) + @RepeatSubmit() + @PutMapping() + public R<Void> edit(@Validated(EditGroup.class) @RequestBody ${ClassName}Bo bo) { + return toAjax(${className}Service.updateByBo(bo)); + } + + /** + * 鍒犻櫎${functionName} + * + * @param ${pkColumn.javaField}s 涓婚敭涓� + */ + @SaCheckPermission("${permissionPrefix}:remove") + @Log(title = "${functionName}", businessType = BusinessType.DELETE) + @DeleteMapping("/{${pkColumn.javaField}s}") + public R<Void> remove(@NotEmpty(message = "涓婚敭涓嶈兘涓虹┖") + @PathVariable ${pkColumn.javaType}[] ${pkColumn.javaField}s) { + return toAjax(${className}Service.deleteWithValidByIds(List.of(${pkColumn.javaField}s), true)); + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/domain.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/domain.java.vm new file mode 100644 index 0000000..b1f8d92 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/domain.java.vm @@ -0,0 +1,59 @@ +package ${packageName}.domain; + +#foreach ($column in $columns) +#if($column.javaField=='tenantId') +#set($IsTenant=1) +#end +#end +#if($IsTenant==1) +import core.tenant.common.org.ruoyi.TenantEntity; +#else +#end +import com.baomidou.mybatisplus.annotation.*; +import lombok.Data; +import lombok.EqualsAndHashCode; +#foreach ($import in $importList) +import ${import}; +#end + +import java.io.Serial; + +/** + * ${functionName}瀵硅薄 ${tableName} + * + * @author ${author} + * @date ${datetime} + */ +#if($IsTenant==1) +#set($Entity="TenantEntity") +#else +#set($Entity="BaseEntity") +#end +@Data +@EqualsAndHashCode(callSuper = true) +@TableName("${tableName}") +public class ${ClassName} extends ${Entity} { + + @Serial + private static final long serialVersionUID = 1L; + +#foreach ($column in $columns) +#if(!$table.isSuperColumn($column.javaField)) + /** + * $column.columnComment + */ +#if($column.javaField=='delFlag') + @TableLogic +#end +#if($column.javaField=='version') + @Version +#end +#if($column.isPk==1) + @TableId(value = "$column.columnName") +#end + private $column.javaType $column.javaField; + +#end +#end + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm new file mode 100644 index 0000000..4eb2b57 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/mapper.java.vm @@ -0,0 +1,15 @@ +package ${packageName}.mapper; + +import ${packageName}.domain.${ClassName}; +import ${packageName}.domain.vo.${ClassName}Vo; +import org.ruoyi.common.mybatis.core.mapper.BaseMapperPlus; + +/** + * ${functionName}Mapper鎺ュ彛 + * + * @author ${author} + * @date ${datetime} + */ +public interface ${ClassName}Mapper extends BaseMapperPlus<${ClassName}, ${ClassName}Vo> { + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/service.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/service.java.vm new file mode 100644 index 0000000..ceb1723 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/service.java.vm @@ -0,0 +1,53 @@ +package ${packageName}.service; + +import ${packageName}.domain.${ClassName}; +import ${packageName}.domain.vo.${ClassName}Vo; +import ${packageName}.domain.bo.${ClassName}Bo; +#if($table.crud || $table.sub) +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +import org.ruoyi.common.mybatis.core.page.PageQuery; +#end + +import java.util.Collection; +import java.util.List; + +/** + * ${functionName}Service鎺ュ彛 + * + * @author ${author} + * @date ${datetime} + */ +public interface I${ClassName}Service { + + /** + * 鏌ヨ${functionName} + */ + ${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField}); + +#if($table.crud || $table.sub) + /** + * 鏌ヨ${functionName}鍒楄〃 + */ + TableDataInfo<${ClassName}Vo> queryPageList(${ClassName}Bo bo, PageQuery pageQuery); +#end + + /** + * 鏌ヨ${functionName}鍒楄〃 + */ + List<${ClassName}Vo> queryList(${ClassName}Bo bo); + + /** + * 鏂板${functionName} + */ + Boolean insertByBo(${ClassName}Bo bo); + + /** + * 淇敼${functionName} + */ + Boolean updateByBo(${ClassName}Bo bo); + + /** + * 鏍¢獙骞舵壒閲忓垹闄�${functionName}淇℃伅 + */ + Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid); +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm new file mode 100644 index 0000000..e8cf3d5 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/serviceImpl.java.vm @@ -0,0 +1,133 @@ +package ${packageName}.service.impl; + +import org.ruoyi.common.core.utils.MapstructUtils; + #if($table.crud || $table.sub) +import org.ruoyi.common.mybatis.core.page.TableDataInfo; +import org.ruoyi.common.mybatis.core.page.PageQuery; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +#end +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import ${packageName}.domain.bo.${ClassName}Bo; +import ${packageName}.domain.vo.${ClassName}Vo; +import ${packageName}.domain.${ClassName}; +import ${packageName}.mapper.${ClassName}Mapper; +import ${packageName}.service.I${ClassName}Service; + +import java.util.List; +import java.util.Map; +import java.util.Collection; + +/** + * ${functionName}Service涓氬姟灞傚鐞� + * + * @author ${author} + * @date ${datetime} + */ +@RequiredArgsConstructor +@Service +public class ${ClassName}ServiceImpl implements I${ClassName}Service { + + private final ${ClassName}Mapper baseMapper; + + /** + * 鏌ヨ${functionName} + */ + @Override + public ${ClassName}Vo queryById(${pkColumn.javaType} ${pkColumn.javaField}){ + return baseMapper.selectVoById(${pkColumn.javaField}); + } + +#if($table.crud || $table.sub) + /** + * 鏌ヨ${functionName}鍒楄〃 + */ + @Override + public TableDataInfo<${ClassName}Vo> queryPageList(${ClassName}Bo bo, PageQuery pageQuery) { + LambdaQueryWrapper<${ClassName}> lqw = buildQueryWrapper(bo); + Page<${ClassName}Vo> result = baseMapper.selectVoPage(pageQuery.build(), lqw); + return TableDataInfo.build(result); + } +#end + + /** + * 鏌ヨ${functionName}鍒楄〃 + */ + @Override + public List<${ClassName}Vo> queryList(${ClassName}Bo bo) { + LambdaQueryWrapper<${ClassName}> lqw = buildQueryWrapper(bo); + return baseMapper.selectVoList(lqw); + } + + private LambdaQueryWrapper<${ClassName}> buildQueryWrapper(${ClassName}Bo bo) { + Map<String, Object> params = bo.getParams(); + LambdaQueryWrapper<${ClassName}> lqw = Wrappers.lambdaQuery(); +#foreach($column in $columns) +#if($column.query) +#set($queryType=$column.queryType) +#set($javaField=$column.javaField) +#set($javaType=$column.javaType) +#set($columnName=$column.columnName) +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +#set($mpMethod=$column.queryType.toLowerCase()) +#if($queryType != 'BETWEEN') +#if($javaType == 'String') +#set($condition='StringUtils.isNotBlank(bo.get'+$AttrName+'())') +#else +#set($condition='bo.get'+$AttrName+'() != null') +#end + lqw.$mpMethod($condition, ${ClassName}::get$AttrName, bo.get$AttrName()); +#else + lqw.between(params.get("begin$AttrName") != null && params.get("end$AttrName") != null, + ${ClassName}::get$AttrName ,params.get("begin$AttrName"), params.get("end$AttrName")); +#end +#end +#end + return lqw; + } + + /** + * 鏂板${functionName} + */ + @Override + public Boolean insertByBo(${ClassName}Bo bo) { + ${ClassName} add = MapstructUtils.convert(bo, ${ClassName}.class); + validEntityBeforeSave(add); + boolean flag = baseMapper.insert(add) > 0; +#set($pk=$pkColumn.javaField.substring(0,1).toUpperCase() + ${pkColumn.javaField.substring(1)}) + if (flag) { + bo.set$pk(add.get$pk()); + } + return flag; + } + + /** + * 淇敼${functionName} + */ + @Override + public Boolean updateByBo(${ClassName}Bo bo) { + ${ClassName} update = MapstructUtils.convert(bo, ${ClassName}.class); + validEntityBeforeSave(update); + return baseMapper.updateById(update) > 0; + } + + /** + * 淇濆瓨鍓嶇殑鏁版嵁鏍¢獙 + */ + private void validEntityBeforeSave(${ClassName} entity){ + //TODO 鍋氫竴浜涙暟鎹牎楠�,濡傚敮涓�绾︽潫 + } + + /** + * 鎵归噺鍒犻櫎${functionName} + */ + @Override + public Boolean deleteWithValidByIds(Collection<${pkColumn.javaType}> ids, Boolean isValid) { + if(isValid){ + //TODO 鍋氫竴浜涗笟鍔′笂鐨勬牎楠�,鍒ゆ柇鏄惁闇�瑕佹牎楠� + } + return baseMapper.deleteBatchIds(ids) > 0; + } +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/vo.java.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/vo.java.vm new file mode 100644 index 0000000..2f41916 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/java/vo.java.vm @@ -0,0 +1,59 @@ +package ${packageName}.domain.vo; + +#foreach ($import in $importList) +import ${import}; +#end +import ${packageName}.domain.${ClassName}; +import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; +import com.alibaba.excel.annotation.ExcelProperty; +import annotation.excel.common.org.ruoyi.ExcelDictFormat; +import convert.excel.common.org.ruoyi.ExcelDictConvert; +import io.github.linpeilie.annotations.AutoMapper; +import lombok.Data; + +import java.io.Serial; +import java.io.Serializable; +import java.util.Date; + + + +/** + * ${functionName}瑙嗗浘瀵硅薄 ${tableName} + * + * @author ${author} + * @date ${datetime} + */ +@Data +@ExcelIgnoreUnannotated +@AutoMapper(target = ${ClassName}.class) +public class ${ClassName}Vo implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + +#foreach ($column in $columns) +#if($column.list) + /** + * $column.columnComment + */ +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if(${column.dictType} && ${column.dictType} != '') + @ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class) + @ExcelDictFormat(dictType = "${column.dictType}") +#elseif($parentheseIndex != -1) + @ExcelProperty(value = "${comment}", converter = ExcelDictConvert.class) + @ExcelDictFormat(readConverterExp = "$column.readConverterExp()") +#else + @ExcelProperty(value = "${comment}") +#end + private $column.javaType $column.javaField; + +#end +#end + +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/js/api.js.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/js/api.js.vm new file mode 100644 index 0000000..9295524 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/js/api.js.vm @@ -0,0 +1,44 @@ +import request from '@/utils/request' + +// 鏌ヨ${functionName}鍒楄〃 +export function list${BusinessName}(query) { + return request({ + url: '/${moduleName}/${businessName}/list', + method: 'get', + params: query + }) +} + +// 鏌ヨ${functionName}璇︾粏 +export function get${BusinessName}(${pkColumn.javaField}) { + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'get' + }) +} + +// 鏂板${functionName} +export function add${BusinessName}(data) { + return request({ + url: '/${moduleName}/${businessName}', + method: 'post', + data: data + }) +} + +// 淇敼${functionName} +export function update${BusinessName}(data) { + return request({ + url: '/${moduleName}/${businessName}', + method: 'put', + data: data + }) +} + +// 鍒犻櫎${functionName} +export function del${BusinessName}(${pkColumn.javaField}) { + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'delete' + }) +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/oracle/sql.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/oracle/sql.vm new file mode 100644 index 0000000..f6638be --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/oracle/sql.vm @@ -0,0 +1,19 @@ +-- 鑿滃崟 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate, null, null, '${functionName}鑿滃崟'); + +-- 鎸夐挳 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[1]}, '${functionName}鏌ヨ', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate, null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[2]}, '${functionName}鏂板', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate, null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[3]}, '${functionName}淇敼', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate, null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[4]}, '${functionName}鍒犻櫎', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate, null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[5]}, '${functionName}瀵煎嚭', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate, null, null, ''); diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/postgres/sql.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/postgres/sql.vm new file mode 100644 index 0000000..0923392 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/postgres/sql.vm @@ -0,0 +1,20 @@ +-- 鑿滃崟 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, now(), null, null, '${functionName}鑿滃崟'); + +-- 鎸夐挳 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[1]}, '${functionName}鏌ヨ', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, now(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[2]}, '${functionName}鏂板', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, now(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[3]}, '${functionName}淇敼', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, now(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[4]}, '${functionName}鍒犻櫎', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, now(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[5]}, '${functionName}瀵煎嚭', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, now(), null, null, ''); + diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sql.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sql.vm new file mode 100644 index 0000000..01824c2 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sql.vm @@ -0,0 +1,19 @@ +-- 鑿滃崟 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, sysdate(), null, null, '${functionName}鑿滃崟'); + +-- 鎸夐挳 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[1]}, '${functionName}鏌ヨ', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, sysdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[2]}, '${functionName}鏂板', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, sysdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[3]}, '${functionName}淇敼', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, sysdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[4]}, '${functionName}鍒犻櫎', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, sysdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[5]}, '${functionName}瀵煎嚭', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, sysdate(), null, null, ''); diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sqlserver/sql.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sqlserver/sql.vm new file mode 100644 index 0000000..bdf166e --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/sql/sqlserver/sql.vm @@ -0,0 +1,19 @@ +-- 鑿滃崟 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[0]}, '${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 103, 1, getdate(), null, null, '${functionName}鑿滃崟'); + +-- 鎸夐挳 SQL +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[1]}, '${functionName}鏌ヨ', ${table.menuIds[0]}, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 103, 1, getdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[2]}, '${functionName}鏂板', ${table.menuIds[0]}, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 103, 1, getdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[3]}, '${functionName}淇敼', ${table.menuIds[0]}, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 103, 1, getdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[4]}, '${functionName}鍒犻櫎', ${table.menuIds[0]}, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 103, 1, getdate(), null, null, ''); + +insert into sys_menu (menu_id, menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_dept, create_by, create_time, update_by, update_time, remark) +values(${table.menuIds[5]}, '${functionName}瀵煎嚭', ${table.menuIds[0]}, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 103, 1, getdate(), null, null, ''); diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/api.ts.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/api.ts.vm new file mode 100644 index 0000000..9ef9ff4 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/api.ts.vm @@ -0,0 +1,63 @@ +import request from '@/utils/request'; +import {AxiosPromise} from 'axios'; +import {${BusinessName}Form, ${BusinessName}Query, ${BusinessName}VO} from '@/api/'; + +/** + * 鏌ヨ${functionName}鍒楄〃 + * @param query + * @returns {*} + */ + +export const list${BusinessName} = (query?: ${BusinessName}Query): AxiosPromise<${BusinessName}VO[]> => { + return request({ + url: '/${moduleName}/${businessName}/list', + method: 'get', + params: query + }); +}; + +/** + * 鏌ヨ${functionName}璇︾粏 + * @param ${pkColumn.javaField} + */ +export const get${BusinessName} = (${pkColumn.javaField}: string | number): AxiosPromise<${BusinessName}VO> => { + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'get' + }); +}; + +/** + * 鏂板${functionName} + * @param data + */ +export const add${BusinessName} = (data: ${BusinessName}Form) => { + return request({ + url: '/${moduleName}/${businessName}', + method: 'post', + data: data + }); +}; + +/** + * 淇敼${functionName} + * @param data + */ +export const update${BusinessName} = (data: ${BusinessName}Form) => { + return request({ + url: '/${moduleName}/${businessName}', + method: 'put', + data: data + }); +}; + +/** + * 鍒犻櫎${functionName} + * @param ${pkColumn.javaField} + */ +export const del${BusinessName} = (${pkColumn.javaField}: string | number | Array<string | number>) => { + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'delete' + }); +}; diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/types.ts.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/types.ts.vm new file mode 100644 index 0000000..99359e0 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/ts/types.ts.vm @@ -0,0 +1,44 @@ +export interface ${BusinessName}VO { +#foreach ($column in $columns) +#if($column.insert || $column.edit) + /** + * $column.columnComment + */ + $column.javaField:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number; + #elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number; + #elseif($column.javaType == 'Boolean') boolean; + #else string; + #end +#end +#end +} + +export interface ${BusinessName}Form extends BaseEntity { +#foreach ($column in $columns) +#if($column.insert || $column.edit) + /** + * $column.columnComment + */ + $column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number; + #elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number; + #elseif($column.javaType == 'Boolean') boolean; + #else string; + #end +#end +#end +} + +export interface ${BusinessName}Query #if(!${treeCode})extends PageQuery #end{ +#foreach ($column in $columns) +#if($column.query) + /** + * $column.columnComment + */ + $column.javaField?:#if($column.javaField.indexOf("id") != -1 || $column.javaField.indexOf("Id") != -1) string | number; + #elseif($column.javaType == 'Long' || $column.javaType == 'Integer' || $column.javaType == 'Double' || $column.javaType == 'Float' || $column.javaType == 'BigDecimal') number; + #elseif($column.javaType == 'Boolean') boolean; + #else string; + #end +#end +#end +} diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm new file mode 100644 index 0000000..dda1b46 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index-tree.vue.vm @@ -0,0 +1,502 @@ +<template> + <div class="p-2"> + <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave"> + <div class="search" v-show="showSearch"> + <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px"> +#foreach($column in $columns) +#if($column.query) +#set($dictType=$column.dictType) +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if($column.htmlType == "input" || $column.htmlType == "textarea") + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-input v-model="queryParams.${column.javaField}" placeholder="璇疯緭鍏�${comment}" clearable @keyup.enter="handleQuery" /> + </el-form-item> +#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType) + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-select v-model="queryParams.${column.javaField}" placeholder="璇烽�夋嫨${comment}" clearable> + <el-option + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.label" + :value="dict.value" + /> + </el-select> + </el-form-item> +#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType) + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-select v-model="queryParams.${column.javaField}" placeholder="璇烽�夋嫨${comment}" clearable> + <el-option label="璇烽�夋嫨瀛楀吀鐢熸垚" value="" /> + </el-select> + </el-form-item> +#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN") + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-date-picker clearable + v-model="queryParams.${column.javaField}" + type="date" + value-format="YYYY-MM-DD" + placeholder="閫夋嫨${comment}" + /> + </el-form-item> +#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN") + <el-form-item label="${comment}" style="width: 308px"> + <el-date-picker + v-model="daterange${AttrName}" + value-format="YYYY-MM-DD HH:mm:ss" + type="daterange" + range-separator="-" + start-placeholder="寮�濮嬫棩鏈�" + end-placeholder="缁撴潫鏃ユ湡" + :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" + /> + </el-form-item> +#end +#end +#end + <el-form-item> + <el-button type="primary" icon="Search" @click="handleQuery">鎼滅储</el-button> + <el-button icon="Refresh" @click="resetQuery">閲嶇疆</el-button> + </el-form-item> + </el-form> + </div> + </transition> + + <el-card shadow="never"> + <template #header> + <el-row :gutter="10" class="mb8"> + <el-col :span="1.5"> + <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['${moduleName}:${businessName}:add']">鏂板</el-button> + </el-col> + <el-col :span="1.5"> + <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">灞曞紑/鎶樺彔</el-button> + </el-col> + <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> + </el-row> + </template> + <el-table + v-loading="loading" + :data="${businessName}List" + row-key="${treeCode}" + :default-expand-all="isExpandAll" + :tree-props="{children: 'children', hasChildren: 'hasChildren'}" + ref="${businessName}TableRef" + > +#foreach($column in $columns) +#set($javaField=$column.javaField) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if($column.pk) +#elseif($column.list && $column.htmlType == "datetime") + <el-table-column label="${comment}" align="center" prop="${javaField}" width="180"> + <template #default="scope"> + <span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span> + </template> + </el-table-column> +#elseif($column.list && $column.htmlType == "imageUpload") + <el-table-column label="${comment}" align="center" prop="${javaField}" width="100"> + <template #default="scope"> + <image-preview :src="scope.row.${javaField}" :width="50" :height="50"/> + </template> + </el-table-column> +#elseif($column.list && $column.dictType && "" != $column.dictType) + <el-table-column label="${comment}" align="center" prop="${javaField}"> + <template #default="scope"> +#if($column.htmlType == "checkbox") + <dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/> +#else + <dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/> +#end + </template> + </el-table-column> +#elseif($column.list && "" != $javaField) +#if(${foreach.index} == 1) + <el-table-column label="${comment}" prop="${javaField}" /> +#else + <el-table-column label="${comment}" align="center" prop="${javaField}" /> +#end +#end +#end + <el-table-column label="鎿嶄綔" align="center" class-name="small-padding fixed-width"> + <template #default="scope"> + <el-tooltip content="淇敼" placement="top"> + <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']" /> + </el-tooltip> + <el-tooltip content="鏂板" placement="top"> + <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['${moduleName}:${businessName}:add']" /> + </el-tooltip> + <el-tooltip content="鍒犻櫎" placement="top"> + <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']" /> + </el-tooltip> + </template> + </el-table-column> + </el-table> + </el-card> + <!-- 娣诲姞鎴栦慨鏀�${functionName}瀵硅瘽妗� --> + <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body> + <el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px"> +#foreach($column in $columns) +#set($field=$column.javaField) +#if($column.insert && !$column.pk) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#set($dictType=$column.dictType) +#if("" != $treeParentCode && $column.javaField == $treeParentCode) + <el-form-item label="${comment}" prop="${treeParentCode}"> + <el-tree-select + v-model="form.${treeParentCode}" + :data="${businessName}Options" + :props="{ value: '${treeCode}', label: '${treeName}', children: 'children' }" + value-key="${treeCode}" + placeholder="璇烽�夋嫨${comment}" + check-strictly + /> + </el-form-item> +#elseif($column.htmlType == "input") + <el-form-item label="${comment}" prop="${field}"> + <el-input v-model="form.${field}" placeholder="璇疯緭鍏�${comment}" /> + </el-form-item> +#elseif($column.htmlType == "imageUpload") + <el-form-item label="${comment}" prop="${field}"> + <image-upload v-model="form.${field}"/> + </el-form-item> +#elseif($column.htmlType == "fileUpload") + <el-form-item label="${comment}" prop="${field}"> + <file-upload v-model="form.${field}"/> + </el-form-item> +#elseif($column.htmlType == "editor") + <el-form-item label="${comment}"> + <editor v-model="form.${field}" :min-height="192"/> + </el-form-item> +#elseif($column.htmlType == "select" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-select v-model="form.${field}" placeholder="璇烽�夋嫨${comment}"> + <el-option + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.label" +#if($column.javaType == "Integer" || $column.javaType == "Long") + :value="parseInt(dict.value)" +#else + :value="dict.value" +#end + ></el-option> + </el-select> + </el-form-item> +#elseif($column.htmlType == "select" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-select v-model="form.${field}" placeholder="璇烽�夋嫨${comment}"> + <el-option label="璇烽�夋嫨瀛楀吀鐢熸垚" value="" /> + </el-select> + </el-form-item> +#elseif($column.htmlType == "checkbox" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-checkbox-group v-model="form.${field}"> + <el-checkbox + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.value"> + {{dict.label}} + </el-checkbox> + </el-checkbox-group> + </el-form-item> +#elseif($column.htmlType == "checkbox" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-checkbox-group v-model="form.${field}"> + <el-checkbox>璇烽�夋嫨瀛楀吀鐢熸垚</el-checkbox> + </el-checkbox-group> + </el-form-item> +#elseif($column.htmlType == "radio" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-radio-group v-model="form.${field}"> + <el-radio + v-for="dict in ${dictType}" + :key="dict.value" +#if($column.javaType == "Integer" || $column.javaType == "Long") + :label="parseInt(dict.value)" +#else + :label="dict.value" +#end + >{{dict.label}}</el-radio> + </el-radio-group> + </el-form-item> +#elseif($column.htmlType == "radio" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-radio-group v-model="form.${field}"> + <el-radio label="1">璇烽�夋嫨瀛楀吀鐢熸垚</el-radio> + </el-radio-group> + </el-form-item> +#elseif($column.htmlType == "datetime") + <el-form-item label="${comment}" prop="${field}"> + <el-date-picker clearable + v-model="form.${field}" + type="datetime" + value-format="YYYY-MM-DD HH:mm:ss" + placeholder="閫夋嫨${comment}" + /> + </el-form-item> +#elseif($column.htmlType == "textarea") + <el-form-item label="${comment}" prop="${field}"> + <el-input v-model="form.${field}" type="textarea" placeholder="璇疯緭鍏ュ唴瀹�" /> + </el-form-item> +#end +#end +#end + </el-form> + <template #footer> + <div class="dialog-footer"> + <el-button :loading="buttonLoading" type="primary" @click="submitForm">纭� 瀹�</el-button> + <el-button @click="cancel">鍙� 娑�</el-button> + </div> + </template> + </el-dialog> + </div> +</template> + +<script setup name="${BusinessName}" lang="ts"> +import { list${BusinessName}, get${BusinessName}, del${BusinessName}, add${BusinessName}, update${BusinessName} } from "@/api/${moduleName}/${businessName}"; +import { ${BusinessName}VO, ${BusinessName}Query, ${BusinessName}Form } from '@/api/${moduleName}/${businessName}/types'; +import { ComponentInternalInstance } from 'vue'; +import { ElForm, ElTable } from 'element-plus'; + + +type ${BusinessName}Option = { + ${treeCode}: number; + ${treeName}: string; + children?: ${BusinessName}Option[]; +} + +const { proxy } = getCurrentInstance() as ComponentInternalInstance;; + +#if(${dicts} != '') +#set($dictsNoSymbol=$dicts.replace("'", "")) +const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts})); +#end + +const ${businessName}List = ref<${BusinessName}VO[]>([]); +const ${businessName}Options = ref<${BusinessName}Option[]>([]); +const buttonLoading = ref(false); +const showSearch = ref(true); +const isExpandAll = ref(true); +const loading = ref(false); + +const queryFormRef = ref(ElForm); +const ${businessName}FormRef = ref(ElForm); +const ${businessName}TableRef = ref(ElTable) + +const dialog = reactive<DialogOption>({ + visible: false, + title: '' +}); + +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +const daterange${AttrName} = ref([]); +#end +#end + +const initFormData: ${BusinessName}Form = { +#foreach ($column in $columns) +#if($column.insert || $column.edit) +#if($column.htmlType == "checkbox") + $column.javaField: []#if($foreach.count != $columns.size()),#end +#else + $column.javaField: undefined#if($foreach.count != $columns.size()),#end +#end +#end +#end +} + +const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({ + form: {...initFormData}, + queryParams: { +#foreach ($column in $columns) +#if($column.query) + $column.javaField: undefined#if($foreach.count != $columns.size()),#end +#end +#end + }, + rules: { +#foreach ($column in $columns) +#if($column.insert || $column.edit) +#if($column.required) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end + $column.javaField: [ + { required: true, message: "$comment涓嶈兘涓虹┖", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end } + ]#if($foreach.count != $columns.size()),#end +#end +#end +#end + } +}); + +const { queryParams, form, rules } = toRefs(data); + +/** 鏌ヨ${functionName}鍒楄〃 */ +const getList = async () => { + loading.value = true; +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") + queryParams.value.params = {}; +#break +#end +#end +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + if (null != daterange${AttrName} && '' != daterange${AttrName}) { + queryParams.value.params["begin${AttrName}"] = daterange${AttrName}.value[0]; + queryParams.value.params["end${AttrName}"] = daterange${AttrName}.value[1]; + } +#end +#end + const res = await list${BusinessName}(queryParams.value); + const data = proxy?.handleTree<${BusinessName}VO>(res.data, "${treeCode}", "${treeParentCode}"); + if (data) { + ${businessName}List.value = data; + loading.value = false; + } +} + +/** 鏌ヨ${functionName}涓嬫媺鏍戠粨鏋� */ +const getTreeselect = async () => { + const res = await list${BusinessName}(); + ${businessName}Options.value = []; + const data: ${BusinessName}Option = { ${treeCode}: 0, ${treeName}: '椤剁骇鑺傜偣', children: [] }; + data.children = proxy?.handleTree<${BusinessName}Option>(res.data, "${treeCode}", "${treeParentCode}"); + ${businessName}Options.value.push(data); +} + +// 鍙栨秷鎸夐挳 +const cancel = () => { + reset(); + dialog.visible = false; +} + +// 琛ㄥ崟閲嶇疆 +const reset = () => { + form.value = {...initFormData} + ${businessName}FormRef.value.resetFields(); +} + +/** 鎼滅储鎸夐挳鎿嶄綔 */ +const handleQuery = () => { + getList(); +} + +/** 閲嶇疆鎸夐挳鎿嶄綔 */ +const resetQuery = () => { +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + daterange${AttrName}.value = []; +#end +#end + queryFormRef.value.resetFields(); + handleQuery(); +} + +/** 鏂板鎸夐挳鎿嶄綔 */ +const handleAdd = (row?: ${BusinessName}VO) => { + dialog.visible = true; + dialog.title = "娣诲姞${functionName}"; + nextTick(() => { + reset(); + getTreeselect(); + if (row != null && row.${treeCode}) { + form.value.${treeParentCode} = row.${treeCode}; + } else { + form.value.${treeParentCode} = 0; + } + }); +} + +/** 灞曞紑/鎶樺彔鎿嶄綔 */ +const handleToggleExpandAll = () => { + isExpandAll.value = !isExpandAll.value; + toggleExpandAll(${businessName}List.value, isExpandAll.value) +} + +/** 灞曞紑/鎶樺彔鎿嶄綔 */ +const toggleExpandAll = (data: ${BusinessName}VO[], status: boolean) => { + data.forEach((item) => { + ${businessName}TableRef.value.toggleRowExpansion(item, status) + if (item.children && item.children.length > 0) toggleExpandAll(item.children, status) + }) +} + +/** 淇敼鎸夐挳鎿嶄綔 */ +const handleUpdate = (row: ${BusinessName}VO) => { + loading.value = true; + dialog.visible = true; + dialog.title = "淇敼${functionName}"; + nextTick(async () => { + reset(); + await getTreeselect(); + if (row != null) { + form.value.${treeParentCode} = row.${treeCode}; + } + const res = await get${BusinessName}(row.${treeCode}); + loading.value = false; + Object.assign(form.value, res.data); +#foreach ($column in $columns) +#if($column.htmlType == "checkbox") + form.value.$column.javaField = form.value.${column.javaField}.split(","); +#end +#end + }); +} + +/** 鎻愪氦鎸夐挳 */ +const submitForm = () => { + ${businessName}FormRef.value.validate((valid: boolean) => { + if (valid) { + buttonLoading.value = true; +#foreach ($column in $columns) +#if($column.htmlType == "checkbox") + form.value.$column.javaField = form.value.${column.javaField}.join(","); +#end +#end + if (form.value.${pkColumn.javaField}) { + update${BusinessName}(form.value).finally(() => buttonLoading.value = false); + } else { + add${BusinessName}(form.value).finally(() => buttonLoading.value = false); + } + proxy?.#[[$modal]]#.msgSuccess("鎿嶄綔鎴愬姛"); + dialog.visible = false; + getList(); + } + }); +} + +/** 鍒犻櫎鎸夐挳鎿嶄綔 */ +const handleDelete = async (row: ${BusinessName}VO) => { + await proxy?.#[[$modal]]#.confirm('鏄惁纭鍒犻櫎${functionName}缂栧彿涓�"' + row.${pkColumn.javaField} + '"鐨勬暟鎹」锛�'); + loading.value = true; + await del${BusinessName}(row.${pkColumn.javaField}).finally(() => loading.value = false); + await getList(); + proxy?.#[[$modal]]#.msgSuccess("鍒犻櫎鎴愬姛"); +} + +onMounted(() => { + getList(); +}); +</script> diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm new file mode 100644 index 0000000..6847f3b --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/vue/index.vue.vm @@ -0,0 +1,475 @@ +<template> + <div class="p-2"> + <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave"> + <div class="search" v-show="showSearch"> + <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px"> +#foreach($column in $columns) +#if($column.query) +#set($dictType=$column.dictType) +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if($column.htmlType == "input" || $column.htmlType == "textarea") + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-input v-model="queryParams.${column.javaField}" placeholder="璇疯緭鍏�${comment}" clearable @keyup.enter="handleQuery" /> + </el-form-item> +#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && "" != $dictType) + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-select v-model="queryParams.${column.javaField}" placeholder="璇烽�夋嫨${comment}" clearable> + <el-option + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.label" + :value="dict.value" + /> + </el-select> + </el-form-item> +#elseif(($column.htmlType == "select" || $column.htmlType == "radio") && $dictType) + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-select v-model="queryParams.${column.javaField}" placeholder="璇烽�夋嫨${comment}" clearable> + <el-option label="璇烽�夋嫨瀛楀吀鐢熸垚" value="" /> + </el-select> + </el-form-item> +#elseif($column.htmlType == "datetime" && $column.queryType != "BETWEEN") + <el-form-item label="${comment}" prop="${column.javaField}"> + <el-date-picker clearable + v-model="queryParams.${column.javaField}" + type="date" + value-format="YYYY-MM-DD" + placeholder="璇烽�夋嫨${comment}" + /> + </el-form-item> +#elseif($column.htmlType == "datetime" && $column.queryType == "BETWEEN") + <el-form-item label="${comment}" style="width: 308px"> + <el-date-picker + v-model="daterange${AttrName}" + value-format="YYYY-MM-DD HH:mm:ss" + type="daterange" + range-separator="-" + start-placeholder="寮�濮嬫棩鏈�" + end-placeholder="缁撴潫鏃ユ湡" + :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" + /> + </el-form-item> +#end +#end +#end + <el-form-item> + <el-button type="primary" icon="Search" @click="handleQuery">鎼滅储</el-button> + <el-button icon="Refresh" @click="resetQuery">閲嶇疆</el-button> + </el-form-item> + </el-form> + </div> + </transition> + + <el-card shadow="never"> + <template #header> + <el-row :gutter="10" class="mb8"> + <el-col :span="1.5"> + <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['${moduleName}:${businessName}:add']">鏂板</el-button> + </el-col> + <el-col :span="1.5"> + <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['${moduleName}:${businessName}:edit']">淇敼</el-button> + </el-col> + <el-col :span="1.5"> + <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['${moduleName}:${businessName}:remove']">鍒犻櫎</el-button> + </el-col> + <el-col :span="1.5"> + <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['${moduleName}:${businessName}:export']">瀵煎嚭</el-button> + </el-col> + <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> + </el-row> + </template> + + <el-table v-loading="loading" :data="${businessName}List" @selection-change="handleSelectionChange"> + <el-table-column type="selection" width="55" align="center" /> +#foreach($column in $columns) +#set($javaField=$column.javaField) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#if($column.pk) + <el-table-column label="${comment}" align="center" prop="${javaField}" v-if="${column.list}" /> +#elseif($column.list && $column.htmlType == "datetime") + <el-table-column label="${comment}" align="center" prop="${javaField}" width="180"> + <template #default="scope"> + <span>{{ parseTime(scope.row.${javaField}, '{y}-{m}-{d}') }}</span> + </template> + </el-table-column> +#elseif($column.list && $column.htmlType == "imageUpload") + <el-table-column label="${comment}" align="center" prop="${javaField}" width="100"> + <template #default="scope"> + <image-preview :src="scope.row.${javaField}" :width="50" :height="50"/> + </template> + </el-table-column> +#elseif($column.list && $column.dictType && "" != $column.dictType) + <el-table-column label="${comment}" align="center" prop="${javaField}"> + <template #default="scope"> +#if($column.htmlType == "checkbox") + <dict-tag :options="${column.dictType}" :value="scope.row.${javaField} ? scope.row.${javaField}.split(',') : []"/> +#else + <dict-tag :options="${column.dictType}" :value="scope.row.${javaField}"/> +#end + </template> + </el-table-column> +#elseif($column.list && "" != $javaField) + <el-table-column label="${comment}" align="center" prop="${javaField}" /> +#end +#end + <el-table-column label="鎿嶄綔" align="center" class-name="small-padding fixed-width"> + <template #default="scope"> + <el-tooltip content="淇敼" placement="top"> + <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['${moduleName}:${businessName}:edit']"></el-button> + </el-tooltip> + <el-tooltip content="鍒犻櫎" placement="top"> + <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['${moduleName}:${businessName}:remove']"></el-button> + </el-tooltip> + </template> + </el-table-column> + </el-table> + + <pagination + v-show="total>0" + :total="total" + v-model:page="queryParams.pageNum" + v-model:limit="queryParams.pageSize" + @pagination="getList" + /> + </el-card> + <!-- 娣诲姞鎴栦慨鏀�${functionName}瀵硅瘽妗� --> + <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body> + <el-form ref="${businessName}FormRef" :model="form" :rules="rules" label-width="80px"> +#foreach($column in $columns) +#set($field=$column.javaField) +#if($column.insert && !$column.pk) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end +#set($dictType=$column.dictType) +#if($column.htmlType == "input") + <el-form-item label="${comment}" prop="${field}"> + <el-input v-model="form.${field}" placeholder="璇疯緭鍏�${comment}" /> + </el-form-item> +#elseif($column.htmlType == "imageUpload") + <el-form-item label="${comment}" prop="${field}"> + <image-upload v-model="form.${field}"/> + </el-form-item> +#elseif($column.htmlType == "fileUpload") + <el-form-item label="${comment}" prop="${field}"> + <file-upload v-model="form.${field}"/> + </el-form-item> +#elseif($column.htmlType == "editor") + <el-form-item label="${comment}"> + <editor v-model="form.${field}" :min-height="192"/> + </el-form-item> +#elseif($column.htmlType == "select" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-select v-model="form.${field}" placeholder="璇烽�夋嫨${comment}"> + <el-option + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.label" +#if($column.javaType == "Integer" || $column.javaType == "Long") + :value="parseInt(dict.value)" +#else + :value="dict.value" +#end + ></el-option> + </el-select> + </el-form-item> +#elseif($column.htmlType == "select" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-select v-model="form.${field}" placeholder="璇烽�夋嫨${comment}"> + <el-option label="璇烽�夋嫨瀛楀吀鐢熸垚" value="" /> + </el-select> + </el-form-item> +#elseif($column.htmlType == "checkbox" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-checkbox-group v-model="form.${field}"> + <el-checkbox + v-for="dict in ${dictType}" + :key="dict.value" + :label="dict.value"> + {{dict.label}} + </el-checkbox> + </el-checkbox-group> + </el-form-item> +#elseif($column.htmlType == "checkbox" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-checkbox-group v-model="form.${field}"> + <el-checkbox>璇烽�夋嫨瀛楀吀鐢熸垚</el-checkbox> + </el-checkbox-group> + </el-form-item> +#elseif($column.htmlType == "radio" && "" != $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-radio-group v-model="form.${field}"> + <el-radio + v-for="dict in ${dictType}" + :key="dict.value" +#if($column.javaType == "Integer" || $column.javaType == "Long") + :label="parseInt(dict.value)" +#else + :label="dict.value" +#end + >{{dict.label}}</el-radio> + </el-radio-group> + </el-form-item> +#elseif($column.htmlType == "radio" && $dictType) + <el-form-item label="${comment}" prop="${field}"> + <el-radio-group v-model="form.${field}"> + <el-radio label="1">璇烽�夋嫨瀛楀吀鐢熸垚</el-radio> + </el-radio-group> + </el-form-item> +#elseif($column.htmlType == "datetime") + <el-form-item label="${comment}" prop="${field}"> + <el-date-picker clearable + v-model="form.${field}" + type="datetime" + value-format="YYYY-MM-DD HH:mm:ss" + placeholder="璇烽�夋嫨${comment}"> + </el-date-picker> + </el-form-item> +#elseif($column.htmlType == "textarea") + <el-form-item label="${comment}" prop="${field}"> + <el-input v-model="form.${field}" type="textarea" placeholder="璇疯緭鍏ュ唴瀹�" /> + </el-form-item> +#end +#end +#end + </el-form> + <template #footer> + <div class="dialog-footer"> + <el-button :loading="buttonLoading" type="primary" @click="submitForm">纭� 瀹�</el-button> + <el-button @click="cancel">鍙� 娑�</el-button> + </div> + </template> + </el-dialog> + </div> +</template> + +<script setup name="${BusinessName}" lang="ts"> + import { + add${BusinessName}, + ${BusinessName}Form, + get${BusinessName}, + list${BusinessName}, + ${BusinessName}Query, + update${BusinessName}, + ${BusinessName}VO + } from '@/api/'; + import {ComponentInternalInstance} from 'vue'; + import {ElForm} from 'element-plus'; + + const { proxy } = getCurrentInstance() as ComponentInternalInstance; +#if(${dicts} != '') +#set($dictsNoSymbol=$dicts.replace("'", "")) +const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts})); +#end + +const ${businessName}List = ref<${BusinessName}VO[]>([]); +const buttonLoading = ref(false); +const loading = ref(true); +const showSearch = ref(true); +const ids = ref<Array<string | number>>([]); +const single = ref(true); +const multiple = ref(true); +const total = ref(0); +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) +const daterange${AttrName} = ref([]); +#end +#end + +const queryFormRef = ref(ElForm); +const ${businessName}FormRef = ref(ElForm); + +const dialog = reactive<DialogOption>({ + visible: false, + title: '' +}); + +const initFormData: ${BusinessName}Form = { +#foreach ($column in $columns) +#if($column.insert || $column.edit) +#if($column.htmlType == "checkbox") + $column.javaField: []#if($foreach.count != $columns.size()),#end +#else + $column.javaField: undefined#if($foreach.count != $columns.size()),#end +#end +#end +#end +} +const data = reactive<PageData<${BusinessName}Form, ${BusinessName}Query>>({ + form: {...initFormData}, + queryParams: { + pageNum: 1, + pageSize: 10, +#foreach ($column in $columns) +#if($column.query) + $column.javaField: undefined#if($foreach.count != $columns.size()),#end +#end +#end + }, + rules: { +#foreach ($column in $columns) +#if($column.insert || $column.edit) +#if($column.required) +#set($parentheseIndex=$column.columnComment.indexOf("锛�")) +#if($parentheseIndex != -1) +#set($comment=$column.columnComment.substring(0, $parentheseIndex)) +#else +#set($comment=$column.columnComment) +#end + $column.javaField: [ + { required: true, message: "$comment涓嶈兘涓虹┖", trigger: #if($column.htmlType == "select" || $column.htmlType == "radio")"change"#else"blur"#end } + ]#if($foreach.count != $columns.size()),#end +#end +#end +#end + } +}); + +const { queryParams, form, rules } = toRefs(data); + +/** 鏌ヨ${functionName}鍒楄〃 */ +const getList = async () => { + loading.value = true; +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") + queryParams.value.params = {}; +#break +#end +#end +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + if (null != daterange${AttrName} && '' != daterange${AttrName}) { + queryParams.value.params["begin${AttrName}"] = daterange${AttrName}.value[0]; + queryParams.value.params["end${AttrName}"] = daterange${AttrName}.value[1]; + } +#end +#end + const res = await list${BusinessName}(queryParams.value); + ${businessName}List.value = res.rows; + total.value = res.total; + loading.value = false; +} + +/** 鍙栨秷鎸夐挳 */ +const cancel = () => { + reset(); + dialog.visible = false; +} + +/** 琛ㄥ崟閲嶇疆 */ +const reset = () => { + form.value = {...initFormData}; + ${businessName}FormRef.value.resetFields(); +} + +/** 鎼滅储鎸夐挳鎿嶄綔 */ +const handleQuery = () => { + queryParams.value.pageNum = 1; + getList(); +} + +/** 閲嶇疆鎸夐挳鎿嶄綔 */ +const resetQuery = () => { +#foreach ($column in $columns) +#if($column.htmlType == "datetime" && $column.queryType == "BETWEEN") +#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + daterange${AttrName}.value = []; +#end +#end + queryFormRef.value.resetFields(); + handleQuery(); +} + +/** 澶氶�夋閫変腑鏁版嵁 */ +const handleSelectionChange = (selection: ${BusinessName}VO[]) => { + ids.value = selection.map(item => item.${pkColumn.javaField}); + single.value = selection.length != 1; + multiple.value = !selection.length; +} + +/** 鏂板鎸夐挳鎿嶄綔 */ +const handleAdd = () => { + dialog.visible = true; + dialog.title = "娣诲姞${functionName}"; + nextTick(() => { + reset(); + }); +} + +/** 淇敼鎸夐挳鎿嶄綔 */ +const handleUpdate = (row?: ${BusinessName}VO) => { + loading.value = true + dialog.visible = true; + dialog.title = "淇敼${functionName}"; + nextTick(async () => { + reset(); + const _${pkColumn.javaField} = row?.${pkColumn.javaField} || ids.value[0] + const res = await get${BusinessName}(_${pkColumn.javaField}); + loading.value = false; + Object.assign(form.value, res.data); +#foreach ($column in $columns) +#if($column.htmlType == "checkbox") + form.value.$column.javaField = form.value.${column.javaField}.split(","); +#end +#end + }); +} + +/** 鎻愪氦鎸夐挳 */ +const submitForm = () => { + ${businessName}FormRef.value.validate(async (valid: boolean) => { + if (valid) { + buttonLoading.value = true; + #foreach ($column in $columns) + #if($column.htmlType == "checkbox") + form.value.$column.javaField = form.value.${column.javaField}.join(","); + #end + #end + if (form.value.${pkColumn.javaField}) { + await update${BusinessName}(form.value).finally(() => buttonLoading.value = false); + } else { + await add${BusinessName}(form.value).finally(() => buttonLoading.value = false); + } + proxy?.#[[$modal]]#.msgSuccess("淇敼鎴愬姛"); + dialog.visible = false; + await getList(); + } + }); +} + +/** 鍒犻櫎鎸夐挳鎿嶄綔 */ +const handleDelete = async (row?: ${BusinessName}VO) => { + const _${pkColumn.javaField}s = row?.${pkColumn.javaField} || ids.value; + await proxy?.#[[$modal]]#.confirm('鏄惁纭鍒犻櫎${functionName}缂栧彿涓�"' + _${pkColumn.javaField}s + '"鐨勬暟鎹」锛�').finally(() => loading.value = false); + await del${BusinessName}(_${pkColumn.javaField}s); + proxy?.#[[$modal]]#.msgSuccess("鍒犻櫎鎴愬姛"); + await getList(); +} + +/** 瀵煎嚭鎸夐挳鎿嶄綔 */ +const handleExport = () => { + proxy?.download('${moduleName}/${businessName}/export', { + ...queryParams.value + }, `${businessName}_#[[${new Date().getTime()}]]#.xlsx`) +} + +onMounted(() => { + getList(); +}); +</script> diff --git a/ruoyi-modules/ruoyi-generator/src/main/resources/vm/xml/mapper.xml.vm b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/xml/mapper.xml.vm new file mode 100644 index 0000000..9fb48d9 --- /dev/null +++ b/ruoyi-modules/ruoyi-generator/src/main/resources/vm/xml/mapper.xml.vm @@ -0,0 +1,7 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!DOCTYPE mapper +PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" +"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> +<mapper namespace="${packageName}.mapper.${ClassName}Mapper"> + +</mapper> diff --git a/script/sql/ruoyi-ai.sql b/script/sql/ruoyi-ai.sql index 152c480..b7ee99e 100644 --- a/script/sql/ruoyi-ai.sql +++ b/script/sql/ruoyi-ai.sql @@ -407,17 +407,17 @@ INSERT INTO `gen_table` VALUES (1661288223925915650, 'sys_user_post', '鐢ㄦ埛涓庡矖浣嶅叧鑱旇〃', NULL, NULL, 'SysUserPost', 'crud', 'org.dromara.system', 'system', 'userPost', '鐢ㄦ埛涓庡矖浣嶅叧鑱�', 'Lion Li', '0', '/', NULL, 103, 1, '2023-05-20 18:05:11', 1, '2023-05-20 18:05:11', NULL); INSERT INTO `gen_table` VALUES (1661288223967858689, 'sys_user_role', '鐢ㄦ埛鍜岃鑹插叧鑱旇〃', NULL, NULL, 'SysUserRole', 'crud', 'org.dromara.system', 'system', 'userRole', '鐢ㄦ埛鍜岃鑹插叧鑱�', 'Lion Li', '0', '/', NULL, 103, 1, '2023-05-20 18:05:11', 1, '2023-05-20 18:05:11', NULL); INSERT INTO `gen_table` VALUES (1661288385096241154, 'sys_config', '鍙傛暟閰嶇疆琛�', NULL, NULL, 'SysConfig', 'crud', 'org.dromara.system', 'system', 'config', '鍙傛暟閰嶇疆', 'Lion Li', '0', '/', NULL, 103, 1, '2023-05-20 18:05:10', 1, '2023-05-20 18:05:10', NULL); -INSERT INTO `gen_table` VALUES (1680196323445579778, 'sys_file_detail', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileDetail', 'crud', 'com.xmzs.system', 'system', 'fileDetail', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:40:00', 1, '2023-07-15 20:40:00', NULL); -INSERT INTO `gen_table` VALUES (1680196323521077249, 'sys_file_detail', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileDetail', 'crud', 'com.xmzs.system', 'system', 'fileDetail', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:40:00', 1, '2023-07-15 20:40:00', NULL); -INSERT INTO `gen_table` VALUES (1680199147407806465, 'sys_file_info', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileInfo', 'crud', 'com.xmzs.system', 'system', 'fileInfo', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:53:56', 1, '2023-07-15 20:53:56', NULL); -INSERT INTO `gen_table` VALUES (1680481752850145282, 'sd_model_param', '妯″瀷鍙傛暟淇℃伅琛�', NULL, NULL, 'SdModelParam', 'crud', 'com.xmzs.system', 'system', 'modelParam', '妯″瀷鍙傛暟淇℃伅', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-16 15:18:34', 1, '2023-07-16 15:18:34', NULL); -INSERT INTO `gen_table` VALUES (1740573614897897473, 'payment_orders', '鏀粯璁㈠崟琛�', NULL, NULL, 'PaymentOrders', 'crud', 'com.xmzs.system', 'system', 'orders', '鏀粯璁㈠崟', 'Lion Li', '0', '/', NULL, 103, 1, '2023-12-27 23:04:45', 1, '2023-12-27 23:04:45', NULL); -INSERT INTO `gen_table` VALUES (1775895242171076610, 'sys_model', '绯荤粺妯″瀷', NULL, NULL, 'SysModel', 'crud', 'com.xmzs.system', 'system', 'model', '绯荤粺妯″瀷', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-04 22:27:08', 1, '2024-04-04 22:27:08', NULL); -INSERT INTO `gen_table` VALUES (1785390411861803009, 'wx_rob_config', '寰俊鏈哄櫒浜虹鐞�', NULL, NULL, 'WxRobConfig', 'crud', 'com.xmzs.system', 'system', 'robConfig', 'robot', 'Lion Li', '0', '/', '{\"treeCode\":null,\"treeName\":null,\"treeParentCode\":null,\"parentMenuId\":null}', 103, 1, '2024-05-01 01:10:04', 1, '2024-05-03 21:00:51', NULL); -INSERT INTO `gen_table` VALUES (1785390413745045505, 'wx_rob_keyword', '', NULL, NULL, 'WxRobKeyword', 'crud', 'com.xmzs.system', 'system', 'robKeyword', '', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-30 23:51:44', 1, '2024-04-30 23:51:44', NULL); -INSERT INTO `gen_table` VALUES (1785390414860730369, 'wx_rob_relation', '', NULL, NULL, 'WxRobRelation', 'crud', 'com.xmzs.system', 'system', 'robRelation', '', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-30 23:51:44', 1, '2024-04-30 23:51:44', NULL); -INSERT INTO `gen_table` VALUES (1786379560181882881, 'chat_voucher', '鐢ㄦ埛鍏戞崲璁板綍', NULL, NULL, 'ChatVoucher', 'crud', 'com.xmzs.system', 'system', 'voucher', '鐢ㄦ埛鍏戞崲璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2024-05-03 20:57:18', 1, '2024-05-03 20:57:18', NULL); -INSERT INTO `gen_table` VALUES (1789155611035381761, 'sys_notice_state', '鐢ㄦ埛闃呰鐘舵�佽〃', NULL, NULL, 'SysNoticeState', 'crud', 'com.xmzs.system', 'system', 'noticeState', '鐢ㄦ埛闃呰鐘舵��', 'Lion Li', '0', '/', NULL, 103, 1, '2024-05-11 12:48:14', 1, '2024-05-11 12:48:14', NULL); +INSERT INTO `gen_table` VALUES (1680196323445579778, 'sys_file_detail', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileDetail', 'crud', 'org.ruoyi.system', 'system', 'fileDetail', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:40:00', 1, '2023-07-15 20:40:00', NULL); +INSERT INTO `gen_table` VALUES (1680196323521077249, 'sys_file_detail', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileDetail', 'crud', 'org.ruoyi.system', 'system', 'fileDetail', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:40:00', 1, '2023-07-15 20:40:00', NULL); +INSERT INTO `gen_table` VALUES (1680199147407806465, 'sys_file_info', '鏂囦欢璁板綍琛�', NULL, NULL, 'SysFileInfo', 'crud', 'org.ruoyi.system', 'system', 'fileInfo', '鏂囦欢璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-15 20:53:56', 1, '2023-07-15 20:53:56', NULL); +INSERT INTO `gen_table` VALUES (1680481752850145282, 'sd_model_param', '妯″瀷鍙傛暟淇℃伅琛�', NULL, NULL, 'SdModelParam', 'crud', 'org.ruoyi.system', 'system', 'modelParam', '妯″瀷鍙傛暟淇℃伅', 'Lion Li', '0', '/', NULL, 103, 1, '2023-07-16 15:18:34', 1, '2023-07-16 15:18:34', NULL); +INSERT INTO `gen_table` VALUES (1740573614897897473, 'payment_orders', '鏀粯璁㈠崟琛�', NULL, NULL, 'PaymentOrders', 'crud', 'org.ruoyi.system', 'system', 'orders', '鏀粯璁㈠崟', 'Lion Li', '0', '/', NULL, 103, 1, '2023-12-27 23:04:45', 1, '2023-12-27 23:04:45', NULL); +INSERT INTO `gen_table` VALUES (1775895242171076610, 'sys_model', '绯荤粺妯″瀷', NULL, NULL, 'SysModel', 'crud', 'org.ruoyi.system', 'system', 'model', '绯荤粺妯″瀷', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-04 22:27:08', 1, '2024-04-04 22:27:08', NULL); +INSERT INTO `gen_table` VALUES (1785390411861803009, 'wx_rob_config', '寰俊鏈哄櫒浜虹鐞�', NULL, NULL, 'WxRobConfig', 'crud', 'org.ruoyi.system', 'system', 'robConfig', 'robot', 'Lion Li', '0', '/', '{\"treeCode\":null,\"treeName\":null,\"treeParentCode\":null,\"parentMenuId\":null}', 103, 1, '2024-05-01 01:10:04', 1, '2024-05-03 21:00:51', NULL); +INSERT INTO `gen_table` VALUES (1785390413745045505, 'wx_rob_keyword', '', NULL, NULL, 'WxRobKeyword', 'crud', 'org.ruoyi.system', 'system', 'robKeyword', '', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-30 23:51:44', 1, '2024-04-30 23:51:44', NULL); +INSERT INTO `gen_table` VALUES (1785390414860730369, 'wx_rob_relation', '', NULL, NULL, 'WxRobRelation', 'crud', 'org.ruoyi.system', 'system', 'robRelation', '', 'Lion Li', '0', '/', NULL, 103, 1, '2024-04-30 23:51:44', 1, '2024-04-30 23:51:44', NULL); +INSERT INTO `gen_table` VALUES (1786379560181882881, 'chat_voucher', '鐢ㄦ埛鍏戞崲璁板綍', NULL, NULL, 'ChatVoucher', 'crud', 'org.ruoyi.system', 'system', 'voucher', '鐢ㄦ埛鍏戞崲璁板綍', 'Lion Li', '0', '/', NULL, 103, 1, '2024-05-03 20:57:18', 1, '2024-05-03 20:57:18', NULL); +INSERT INTO `gen_table` VALUES (1789155611035381761, 'sys_notice_state', '鐢ㄦ埛闃呰鐘舵�佽〃', NULL, NULL, 'SysNoticeState', 'crud', 'org.ruoyi.system', 'system', 'noticeState', '鐢ㄦ埛闃呰鐘舵��', 'Lion Li', '0', '/', NULL, 103, 1, '2024-05-11 12:48:14', 1, '2024-05-11 12:48:14', NULL); -- ---------------------------- -- Table structure for gen_table_column -- Gitblit v1.9.3