diff --git a/lms/nladmin-system/src/main/java/org/nl/common/utils/ColUtil.java b/lms/nladmin-system/src/main/java/org/nl/common/utils/ColUtil.java new file mode 100644 index 000000000..ad0aa1d1a --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/common/utils/ColUtil.java @@ -0,0 +1,35 @@ +package org.nl.common.utils; + +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ColUtil { + private static final Logger log = LoggerFactory.getLogger(ColUtil.class); + + /** + * 转换mysql数据类型为java数据类型 + * + * @param type 数据库字段类型 + * @return String + */ + static String cloToJava(String type) { + Configuration config = getConfig(); + assert config != null; + return config.getString(type, "unknowType"); + } + + /** + * 获取配置信息 + */ + public static PropertiesConfiguration getConfig() { + try { + return new PropertiesConfiguration("generator.properties"); + } catch (ConfigurationException e) { + log.error(e.getMessage(), e); + } + return null; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/common/utils/GenUtil.java b/lms/nladmin-system/src/main/java/org/nl/common/utils/GenUtil.java new file mode 100644 index 000000000..c7cc426d0 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/common/utils/GenUtil.java @@ -0,0 +1,439 @@ +package org.nl.common.utils; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.extra.template.*; +import lombok.extern.slf4j.Slf4j; +import org.nl.modules.common.utils.FileUtil; +import org.nl.modules.common.utils.StringUtils; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.springframework.util.ObjectUtils; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.nl.modules.common.utils.FileUtil.SYS_TEM_DIR; + + +/** + * @author: lyd + * @description: 代码生成 + * @Date: 2022/12/2 + */ +@Slf4j +@SuppressWarnings({"unchecked", "all"}) +public class GenUtil { + private static final String TIMESTAMP = "Timestamp"; + + private static final String Date = "Date"; + + private static final String BIGDECIMAL = "BigDecimal"; + + public static final String PK = "PRI"; + + public static final String EXTRA = "auto_increment"; + + /** + * 获取后端代码模板名称 + * + * @return List + */ + private static List getAdminTemplateNames() { + List templateNames = new ArrayList<>(); + templateNames.add("Entity"); + templateNames.add("MySQLMapper"); + templateNames.add("Dto"); + templateNames.add("Mapper"); + templateNames.add("Controller"); + templateNames.add("QueryCriteria"); + templateNames.add("Service"); + templateNames.add("ServiceImpl"); + // templateNames.add("Repository"); + return templateNames; + } + + /** + * 获取前端代码模板名称 + * + * @return List + */ + private static List getFrontTemplateNames() { + List templateNames = new ArrayList<>(); + templateNames.add("index"); + templateNames.add("api"); + return templateNames; + } + + public static List> preview(List columns, CodeGenConfig genConfig) { + Map genMap = getGenMap(columns, genConfig); // 获取参数 + List> genList = new ArrayList<>(); + // 获取后端模版 + List templates = getAdminTemplateNames(); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + for (String templateName : templates) { // 创建模板 + Map map = new HashMap<>(1); + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + map.put("content", template.render(genMap)); + map.put("name", templateName); + genList.add(map); + } + // 获取前端模版 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Map map = new HashMap<>(1); + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + map.put(templateName, template.render(genMap)); + map.put("content", template.render(genMap)); + map.put("name", templateName); + genList.add(map); + } + return genList; + } + + /** + * 定义后端文件路径以及名称 + */ + private static String getAdminFilePath(String templateName, CodeGenConfig genConfig, String className, String rootPath) { + String projectPath = rootPath + File.separator; + String packagePath = projectPath + "src" + File.separator + "main" + File.separator + "java" + File.separator; + if (!ObjectUtils.isEmpty(genConfig.getPack())) { + packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; + } + + if ("Entity".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + className + ".java"; + } + + if ("Controller".equals(templateName)) { + return packagePath + "controller" + File.separator + className + "Controller.java"; + } + + if ("Service".equals(templateName)) { + return packagePath + "service" + File.separator + "I" + className + "Service.java"; + } + + if ("ServiceImpl".equals(templateName)) { + return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; + } + + if ("Dto".equals(templateName)) { + return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; + } + + if ("QueryCriteria".equals(templateName)) { + return packagePath + "service" + File.separator + "dto" + File.separator + className + "Query.java"; + } + + if ("Mapper".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + "mapper" + File.separator + className + "Mapper.java"; + } + + if ("MySQLMapper".equals(templateName)) { + return packagePath + "service" + File.separator + "dao" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; + } + + return null; + } + + /** + * 定义前端文件路径以及名称 + */ + private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { + + if ("api".equals(templateName)) { + return path + File.separator + apiName + ".js"; + } + + if ("index".equals(templateName)) { + return path + File.separator + "index.vue"; + } + + return null; + } + + // 获取模版数据 + private static Map getGenMap(List columnInfos, CodeGenConfig genConfig) { + // 存储模版字段数据 + Map genMap = new HashMap<>(16); + // 接口别名 + genMap.put("apiAlias", genConfig.getApiAlias()); + // 包名称 + genMap.put("package", genConfig.getPack()); + // 模块名称 + genMap.put("moduleName", genConfig.getModuleName()); + // 作者 + genMap.put("author", genConfig.getAuthor()); + // 创建日期 + genMap.put("date", LocalDate.now().toString()); + // 表名 + genMap.put("tableName", genConfig.getTableName()); + // 大写开头的类名 + String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); + // 小写开头的类名 + String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); + // 判断是否去除表前缀 + if (StrUtil.isNotEmpty(genConfig.getPrefix())) { + className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); + changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); + } + // 保存类名 + genMap.put("className", className); // 驼峰命名 + // 保存小写开头的类名 + genMap.put("changeClassName", changeClassName); + // 存在 Timestamp 字段 + genMap.put("hasTimestamp", false); + // 查询类中存在 Timestamp 字段 + genMap.put("queryHasTimestamp", false); + // 存在 BigDecimal 字段 + genMap.put("hasBigDecimal", false); + // 查询类中存在 BigDecimal 字段 + genMap.put("queryHasBigDecimal", false); + // 是否需要创建查询 + genMap.put("hasQuery", false); + // 是否有主键 + genMap.put("hasPk", false); + // 自增主键 + genMap.put("auto", false); + genMap.put("hasDate", false); + // 存在字典 + genMap.put("hasDict", false); + // 存在日期注解 + genMap.put("hasDateAnnotation", false); + // 保存字段信息 + List> columns = new ArrayList<>(); + // 保存查询字段的信息 + List> queryColumns = new ArrayList<>(); + // 存储字典信息 + List dicts = new ArrayList<>(); + // 存储 between 信息 + List> betweens = new ArrayList<>(); + // 存储不为空的字段信息 + List> isNotNullColumns = new ArrayList<>(); + + for (CodeColumnConfig column : columnInfos) { // 遍历所有字段 + Map listMap = new HashMap<>(16); + // 字段描述 + listMap.put("remark", column.getRemark()); + // 字段类型 + listMap.put("columnKey", column.getKeyType()); + // 主键类型 + String colType = ColUtil.cloToJava(column.getColumnType()); + // 小写开头的字段名 - 转驼峰 +// String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); + String changeColumnName = column.getColumnName(); + // 大写开头的字段名 + String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); + if (PK.equals(column.getKeyType())) { // 如果是主键 + genMap.put("hasPk", true); + // 存储主键类型 + genMap.put("pkColumnType", colType); + // 存储小写开头的字段名 + genMap.put("pkChangeColName", changeColumnName); + // 存储大写开头的字段名 + genMap.put("pkCapitalColName", capitalColumnName); + } + // 是否存在 Timestamp 类型的字段 + if (TIMESTAMP.equals(colType)) { + genMap.put("hasTimestamp", true); + } + // 是否存在 BigDecimal 类型的字段 + if (BIGDECIMAL.equals(colType)) { + genMap.put("hasBigDecimal", true); + } + // 主键是否自增 + if (EXTRA.equals(column.getExtra())) { + genMap.put("auto", true); + } + // 主键存在字典 + if (StrUtil.isNotEmpty(column.getDictName())) { + genMap.put("hasDict", true); + dicts.add(column.getDictName()); + } + + // 存储字段类型 + listMap.put("columnType", colType); + // 存储字原始段名称 + listMap.put("columnName", column.getColumnName()); + // 不为空 + listMap.put("istNotNull", column.getNotNull()); + // 字段列表显示 + listMap.put("columnShow", column.getListShow()); + // 表单显示 + listMap.put("formShow", column.getFormShow()); + // 表单组件类型 + listMap.put("formType", StrUtil.isNotEmpty(column.getFormType()) ? column.getFormType() : "Input"); + // 小写开头的字段名称 + listMap.put("changeColumnName", changeColumnName); + //大写开头的字段名称 + listMap.put("capitalColumnName", capitalColumnName); + // 字典名称 + listMap.put("dictName", column.getDictName()); + // 日期注解 + listMap.put("dateAnnotation", column.getDateAnnotation()); + if (StrUtil.isNotEmpty(column.getDateAnnotation())) { + genMap.put("hasDateAnnotation", true); + } + // 添加非空字段信息 + if (column.getNotNull()) { + isNotNullColumns.add(listMap); + } + // 判断是否有查询,如有则把查询的字段set进columnQuery + if (!StrUtil.isEmpty(column.getQueryType())) { + // 查询类型 + listMap.put("queryType", column.getQueryType()); + // 是否存在查询 + genMap.put("hasQuery", true); + if (TIMESTAMP.equals(colType)) { + // 查询中存储 Timestamp 类型 + genMap.put("queryHasTimestamp", true); + } + if (BIGDECIMAL.equals(colType)) { + // 查询中存储 BigDecimal 类型 + genMap.put("queryHasBigDecimal", true); + } + if ("between".equalsIgnoreCase(column.getQueryType())) { + betweens.add(listMap); + } else { + // 添加到查询列表中 + queryColumns.add(listMap); + } + } + // 添加到字段列表中 + columns.add(listMap); + } + // 保存字段列表 + genMap.put("columns", columns); + // 保存查询列表 + genMap.put("queryColumns", queryColumns); + // 保存字段列表 + genMap.put("dicts", dicts); + // 保存查询列表 + genMap.put("betweens", betweens); + // 保存非空字段信息 + genMap.put("isNotNullColumns", isNotNullColumns); + return genMap; + } + + /** + * 打包下载 + * + * @param columns + * @param genConfig + * @return + * @throws IOException + */ + public static String download(List columns, CodeGenConfig genConfig) throws IOException { + // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ + // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; + String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; + Map genMap = getGenMap(columns, genConfig); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + // 生成后端代码 + List templates = getAdminTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); + assert filePath != null; + File file = new File(filePath); + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + // 生成前端代码 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + String path = tempPath + "nladmin-web" + File.separator; + String apiPath = path + "src" + File.separator + "api" + File.separator; + String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; + String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); + assert filePath != null; + File file = new File(filePath); + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + return tempPath; + } + + /** + * 生成文件 + * + * @param file + * @param template + * @param map + * @throws IOException + */ + private static void genFile(File file, Template template, Map map) throws IOException { + // 生成目标文件 + Writer writer = null; + try { + FileUtil.touch(file); + writer = new FileWriter(file); + template.render(map, writer); + } catch (TemplateException | IOException e) { + throw new RuntimeException(e); + } finally { + assert writer != null; + writer.close(); + } + } + + /** + * 生成代码 + * + * @param columnInfos + * @param genConfig + * @throws IOException + */ + public static void generatorCode(List columnInfos, CodeGenConfig genConfig) throws IOException { + Map genMap = getGenMap(columnInfos, genConfig); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + // 生成后端代码 + List templates = getAdminTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), System.getProperty("user.dir")); + + assert filePath != null; + File file = new File(filePath); + + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + + // 生成前端代码 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); + + assert filePath != null; + File file = new File(filePath); + + // 如果非覆盖生成 + if (!genConfig.getCover() && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); + } + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java index e0b008568..71f527e7d 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java @@ -1,99 +1,99 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain; - - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.nl.modules.generator.utils.GenUtil; - -import javax.persistence.*; -import java.io.Serializable; - -/** - * 列的数据信息 - * - * @author Zheng Jie - * @date 2019-01-02 - */ -@Getter -@Setter -@Entity -@NoArgsConstructor -@Table(name = "code_column_config") -public class ColumnInfo implements Serializable { - - @Id - @Column(name = "column_id") - - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - - private String tableName; - - - private String columnName; - - - private String columnType; - - - private String keyType; - - - private String extra; - - - private String remark; - - - private Boolean notNull; - - - private Boolean listShow; - - - private Boolean formShow; - - - private String formType; - - - private String queryType; - - - private String dictName; - - - private String dateAnnotation; - - public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { - this.tableName = tableName; - this.columnName = columnName; - this.columnType = columnType; - this.keyType = keyType; - this.extra = extra; - this.notNull = notNull; - if (GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)) { - this.notNull = false; - } - this.remark = remark; - this.listShow = true; - this.formShow = true; - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.domain; +// +// +//import lombok.Getter; +//import lombok.NoArgsConstructor; +//import lombok.Setter; +//import org.nl.common.utils.GenUtil; +// +//import javax.persistence.*; +//import java.io.Serializable; +// +///** +// * 列的数据信息 +// * +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//@Getter +//@Setter +//@Entity +//@NoArgsConstructor +//@Table(name = "code_column_config") +//public class ColumnInfo implements Serializable { +// +// @Id +// @Column(name = "column_id") +// +// @GeneratedValue(strategy = GenerationType.IDENTITY) +// private Long id; +// +// +// private String tableName; +// +// +// private String columnName; +// +// +// private String columnType; +// +// +// private String keyType; +// +// +// private String extra; +// +// +// private String remark; +// +// +// private Boolean notNull; +// +// +// private Boolean listShow; +// +// +// private Boolean formShow; +// +// +// private String formType; +// +// +// private String queryType; +// +// +// private String dictName; +// +// +// private String dateAnnotation; +// +// public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { +// this.tableName = tableName; +// this.columnName = columnName; +// this.columnType = columnType; +// this.keyType = keyType; +// this.extra = extra; +// this.notNull = notNull; +// if (GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)) { +// this.notNull = false; +// } +// this.remark = remark; +// this.listShow = true; +// this.formShow = true; +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java index 448f672ef..b239ca2de 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java @@ -1,80 +1,80 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain; - - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import javax.persistence.*; -import javax.validation.constraints.NotBlank; -import java.io.Serializable; - -/** - * 代码生成配置 - * - * @author Zheng Jie - * @date 2019-01-03 - */ -@Getter -@Setter -@Entity -@NoArgsConstructor -@Table(name = "code_gen_config") -public class GenConfig implements Serializable { - - public GenConfig(String tableName) { - this.tableName = tableName; - } - - @Id - @Column(name = "config_id") - - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @NotBlank - - private String tableName; - - - private String apiAlias; - - @NotBlank - - private String pack; - - @NotBlank - - private String moduleName; - - @NotBlank - - private String path; - - - private String apiPath; - - - private String author; - - - private String prefix; - - - private Boolean cover = false; -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.domain; +// +// +//import lombok.Getter; +//import lombok.NoArgsConstructor; +//import lombok.Setter; +// +//import javax.persistence.*; +//import javax.validation.constraints.NotBlank; +//import java.io.Serializable; +// +///** +// * 代码生成配置 +// * +// * @author Zheng Jie +// * @date 2019-01-03 +// */ +//@Getter +//@Setter +//@Entity +//@NoArgsConstructor +//@Table(name = "code_gen_config") +//public class GenConfig implements Serializable { +// +// public GenConfig(String tableName) { +// this.tableName = tableName; +// } +// +// @Id +// @Column(name = "config_id") +// +// @GeneratedValue(strategy = GenerationType.IDENTITY) +// private Long id; +// +// @NotBlank +// +// private String tableName; +// +// +// private String apiAlias; +// +// @NotBlank +// +// private String pack; +// +// @NotBlank +// +// private String moduleName; +// +// @NotBlank +// +// private String path; +// +// +// private String apiPath; +// +// +// private String author; +// +// +// private String prefix; +// +// +// private Boolean cover = false; +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java index bd324cb08..29cffd3d7 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java @@ -1,59 +1,59 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain.vo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * 表的数据信息 - * - * @author Zheng Jie - * @date 2019-01-02 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class TableInfo { - - /** - * 表名称 - */ - private Object tableName; - - /** - * 创建日期 - */ - private Object createTime; - - /** - * 数据库引擎 - */ - private Object engine; - - /** - * 编码集 - */ - private Object coding; - - /** - * 备注 - */ - private Object remark; - - -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.domain.vo; +// +//import lombok.AllArgsConstructor; +//import lombok.Data; +//import lombok.NoArgsConstructor; +// +///** +// * 表的数据信息 +// * +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//@Data +//@AllArgsConstructor +//@NoArgsConstructor +//public class TableInfo { +// +// /** +// * 表名称 +// */ +// private Object tableName; +// +// /** +// * 创建日期 +// */ +// private Object createTime; +// +// /** +// * 数据库引擎 +// */ +// private Object engine; +// +// /** +// * 编码集 +// */ +// private Object coding; +// +// /** +// * 备注 +// */ +// private Object remark; +// +// +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java index 2931b4afe..2ff37d29b 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java @@ -1,36 +1,36 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.repository; - -import org.nl.modules.generator.domain.ColumnInfo; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface ColumnInfoRepository extends JpaRepository { - - /** - * 查询表信息 - * - * @param tableName 表格名 - * @return 表信息 - */ - List findByTableNameOrderByIdAsc(String tableName); -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.repository; +// +//import org.nl.modules.generator.domain.ColumnInfo; +//import org.springframework.data.jpa.repository.JpaRepository; +// +//import java.util.List; +// +///** +// * @author Zheng Jie +// * @date 2019-01-14 +// */ +//public interface ColumnInfoRepository extends JpaRepository { +// +// /** +// * 查询表信息 +// * +// * @param tableName 表格名 +// * @return 表信息 +// */ +// List findByTableNameOrderByIdAsc(String tableName); +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java index 395ae8069..35fee49ce 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java @@ -1,34 +1,34 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.repository; - -import org.nl.modules.generator.domain.GenConfig; -import org.springframework.data.jpa.repository.JpaRepository; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface GenConfigRepository extends JpaRepository { - - /** - * 查询表配置 - * - * @param tableName 表名 - * @return / - */ - GenConfig findByTableName(String tableName); -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.repository; +// +//import org.nl.modules.generator.domain.GenConfig; +//import org.springframework.data.jpa.repository.JpaRepository; +// +///** +// * @author Zheng Jie +// * @date 2019-01-14 +// */ +//public interface GenConfigRepository extends JpaRepository { +// +// /** +// * 查询表配置 +// * +// * @param tableName 表名 +// * @return / +// */ +// GenConfig findByTableName(String tableName); +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java index 64c0619b2..0f1b142b2 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java @@ -1,50 +1,50 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.rest; - - -import lombok.RequiredArgsConstructor; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.service.GenConfigService; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.*; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -@RestController -@RequiredArgsConstructor -@RequestMapping("/api/genConfig") - -public class GenConfigController { - - private final GenConfigService genConfigService; - - - @GetMapping(value = "/{tableName}") - public ResponseEntity query(@PathVariable String tableName) { - return new ResponseEntity<>(genConfigService.find(tableName), HttpStatus.OK); - } - - - @PutMapping - public ResponseEntity update(@Validated @RequestBody GenConfig genConfig) { - return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig), HttpStatus.OK); - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.rest; +// +// +//import lombok.RequiredArgsConstructor; +//import org.nl.modules.generator.domain.GenConfig; +//import org.nl.modules.generator.service.GenConfigService; +//import org.springframework.http.HttpStatus; +//import org.springframework.http.ResponseEntity; +//import org.springframework.validation.annotation.Validated; +//import org.springframework.web.bind.annotation.*; +// +///** +// * @author Zheng Jie +// * @date 2019-01-14 +// */ +//@RestController +//@RequiredArgsConstructor +//@RequestMapping("/api/genConfig2") +// +//public class GenConfigController { +// +// private final GenConfigService genConfigService; +// +// +// @GetMapping(value = "/{tableName}") +// public ResponseEntity query(@PathVariable String tableName) { +// return new ResponseEntity<>(genConfigService.find(tableName), HttpStatus.OK); +// } +// +// +// @PutMapping +// public ResponseEntity update(@Validated @RequestBody GenConfig genConfig) { +// return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig), HttpStatus.OK); +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java index eab6e43aa..0abe055ce 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java @@ -1,111 +1,111 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.rest; - - -import lombok.RequiredArgsConstructor; -import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.PageUtil; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.service.GenConfigService; -import org.nl.modules.generator.service.GeneratorService; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-02 - */ -@RestController -@RequiredArgsConstructor -@RequestMapping("/api/generator") - -public class GeneratorController { - - private final GeneratorService generatorService; - private final GenConfigService genConfigService; - - @Value("${generator.enabled}") - private Boolean generatorEnabled; - - - @GetMapping(value = "/tables/all") - public ResponseEntity queryTables() { - return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK); - } - - - @GetMapping(value = "/tables") - public ResponseEntity queryTables(@RequestParam(defaultValue = "") String name, - @RequestParam(defaultValue = "0") Integer page, - @RequestParam(defaultValue = "10") Integer size) { - int[] startEnd = PageUtil.transToStartEnd(page, size); - return new ResponseEntity<>(generatorService.getTables(name, startEnd), HttpStatus.OK); - } - - - @GetMapping(value = "/columns") - public ResponseEntity queryColumns(@RequestParam String tableName) { - List columnInfos = generatorService.getColumns(tableName); - return new ResponseEntity<>(PageUtil.toPage(columnInfos, columnInfos.size()), HttpStatus.OK); - } - - - @PutMapping - public ResponseEntity save(@RequestBody List columnInfos) { - generatorService.save(columnInfos); - return new ResponseEntity<>(HttpStatus.OK); - } - - - @PostMapping(value = "sync") - public ResponseEntity sync(@RequestBody List tables) { - for (String table : tables) { - generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); - } - return new ResponseEntity<>(HttpStatus.OK); - } - - - @PostMapping(value = "/{tableName}/{type}") - public ResponseEntity generator(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) { - if (!generatorEnabled && type == 0) { - throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); - } - switch (type) { - // 生成代码 - case 0: - generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); - break; - // 预览 - case 1: - return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); - // 打包 - case 2: - generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); - break; - default: - throw new BadRequestException("没有这个选项"); - } - return new ResponseEntity<>(HttpStatus.OK); - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.rest; +// +// +//import lombok.RequiredArgsConstructor; +//import org.nl.modules.common.exception.BadRequestException; +//import org.nl.modules.common.utils.PageUtil; +//import org.nl.modules.generator.domain.ColumnInfo; +//import org.nl.modules.generator.service.GenConfigService; +//import org.nl.modules.generator.service.GeneratorService; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.http.HttpStatus; +//import org.springframework.http.ResponseEntity; +//import org.springframework.web.bind.annotation.*; +// +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.util.List; +// +///** +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//@RestController +//@RequiredArgsConstructor +//@RequestMapping("/api/generator2") +// +//public class GeneratorController { +// +// private final GeneratorService generatorService; +// private final GenConfigService genConfigService; +// +// @Value("${generator.enabled}") +// private Boolean generatorEnabled; +// +// +// @GetMapping(value = "/tables/all") +// public ResponseEntity queryTables() { +// return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK); +// } +// +// +// @GetMapping(value = "/tables") +// public ResponseEntity queryTables(@RequestParam(defaultValue = "") String name, +// @RequestParam(defaultValue = "0") Integer page, +// @RequestParam(defaultValue = "10") Integer size) { +// int[] startEnd = PageUtil.transToStartEnd(page, size); +// return new ResponseEntity<>(generatorService.getTables(name, startEnd), HttpStatus.OK); +// } +// +// +// @GetMapping(value = "/columns") +// public ResponseEntity queryColumns(@RequestParam String tableName) { +// List columnInfos = generatorService.getColumns(tableName); +// return new ResponseEntity<>(PageUtil.toPage(columnInfos, columnInfos.size()), HttpStatus.OK); +// } +// +// +// @PutMapping +// public ResponseEntity save(@RequestBody List columnInfos) { +// generatorService.save(columnInfos); +// return new ResponseEntity<>(HttpStatus.OK); +// } +// +// +// @PostMapping(value = "sync") +// public ResponseEntity sync(@RequestBody List tables) { +// for (String table : tables) { +// generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); +// } +// return new ResponseEntity<>(HttpStatus.OK); +// } +// +// +// @PostMapping(value = "/{tableName}/{type}") +// public ResponseEntity generator(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) { +// if (!generatorEnabled && type == 0) { +// throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); +// } +// switch (type) { +// // 生成代码 +// case 0: +// generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); +// break; +// // 预览 +// case 1: +// return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); +// // 打包 +// case 2: +// generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); +// break; +// default: +// throw new BadRequestException("没有这个选项"); +// } +// return new ResponseEntity<>(HttpStatus.OK); +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java index 31efaa39f..009ba5941 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java @@ -1,42 +1,42 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service; - -import org.nl.modules.generator.domain.GenConfig; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface GenConfigService { - - /** - * 查询表配置 - * - * @param tableName 表名 - * @return 表配置 - */ - GenConfig find(String tableName); - - /** - * 更新表配置 - * - * @param tableName 表名 - * @param genConfig 表配置 - * @return 表配置 - */ - GenConfig update(String tableName, GenConfig genConfig); -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.service; +// +//import org.nl.modules.generator.domain.GenConfig; +// +///** +// * @author Zheng Jie +// * @date 2019-01-14 +// */ +//public interface GenConfigService { +// +// /** +// * 查询表配置 +// * +// * @param tableName 表名 +// * @return 表配置 +// */ +// GenConfig find(String tableName); +// +// /** +// * 更新表配置 +// * +// * @param tableName 表名 +// * @param genConfig 表配置 +// * @return 表配置 +// */ +// GenConfig update(String tableName, GenConfig genConfig); +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java index e71fa10d5..d0551542d 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java @@ -1,107 +1,107 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service; - -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; -import org.springframework.http.ResponseEntity; -import org.springframework.scheduling.annotation.Async; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-02 - */ -public interface GeneratorService { - - /** - * 查询数据库元数据 - * - * @param name 表名 - * @param startEnd 分页参数 - * @return / - */ - Object getTables(String name, int[] startEnd); - - /** - * 得到数据表的元数据 - * - * @param name 表名 - * @return / - */ - List getColumns(String name); - - /** - * 同步表数据 - * - * @param columnInfos / - * @param columnInfoList / - */ - @Async - void sync(List columnInfos, List columnInfoList); - - /** - * 保持数据 - * - * @param columnInfos / - */ - void save(List columnInfos); - - /** - * 获取所有table - * - * @return / - */ - Object getTables(); - - /** - * 代码生成 - * - * @param genConfig 配置信息 - * @param columns 字段信息 - */ - void generator(GenConfig genConfig, List columns); - - /** - * 预览 - * - * @param genConfig 配置信息 - * @param columns 字段信息 - * @return / - */ - ResponseEntity preview(GenConfig genConfig, List columns); - - /** - * 打包下载 - * - * @param genConfig 配置信息 - * @param columns 字段信息 - * @param request / - * @param response / - */ - void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response); - - /** - * 查询数据库的表字段数据数据 - * - * @param table / - * @return / - */ - List query(String table); -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.service; +// +//import org.nl.modules.generator.domain.ColumnInfo; +//import org.nl.modules.generator.domain.GenConfig; +//import org.springframework.http.ResponseEntity; +//import org.springframework.scheduling.annotation.Async; +// +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.util.List; +// +///** +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//public interface GeneratorService { +// +// /** +// * 查询数据库元数据 +// * +// * @param name 表名 +// * @param startEnd 分页参数 +// * @return / +// */ +// Object getTables(String name, int[] startEnd); +// +// /** +// * 得到数据表的元数据 +// * +// * @param name 表名 +// * @return / +// */ +// List getColumns(String name); +// +// /** +// * 同步表数据 +// * +// * @param columnInfos / +// * @param columnInfoList / +// */ +// @Async +// void sync(List columnInfos, List columnInfoList); +// +// /** +// * 保持数据 +// * +// * @param columnInfos / +// */ +// void save(List columnInfos); +// +// /** +// * 获取所有table +// * +// * @return / +// */ +// Object getTables(); +// +// /** +// * 代码生成 +// * +// * @param genConfig 配置信息 +// * @param columns 字段信息 +// */ +// void generator(GenConfig genConfig, List columns); +// +// /** +// * 预览 +// * +// * @param genConfig 配置信息 +// * @param columns 字段信息 +// * @return / +// */ +// ResponseEntity preview(GenConfig genConfig, List columns); +// +// /** +// * 打包下载 +// * +// * @param genConfig 配置信息 +// * @param columns 字段信息 +// * @param request / +// * @param response / +// */ +// void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response); +// +// /** +// * 查询数据库的表字段数据数据 +// * +// * @param table / +// * @return / +// */ +// List query(String table); +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java index 80c0b3890..0728b9761 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java @@ -1,71 +1,71 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service.impl; - -import cn.hutool.core.util.StrUtil; -import lombok.RequiredArgsConstructor; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.repository.GenConfigRepository; -import org.nl.modules.generator.service.GenConfigService; -import org.springframework.stereotype.Service; - -import java.io.File; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -@Service -@RequiredArgsConstructor -public class GenConfigServiceImpl implements GenConfigService { - - private final GenConfigRepository genConfigRepository; - - @Override - public GenConfig find(String tableName) { - GenConfig genConfig = genConfigRepository.findByTableName(tableName); - if (genConfig == null) { - return new GenConfig(tableName); - } - return genConfig; - } - - @Override - public GenConfig update(String tableName, GenConfig genConfig) { - // 如果 api 路径为空,则自动生成路径 - if (StrUtil.isEmpty(genConfig.getApiPath())) { - String separator = File.separator; - String[] paths; - String symbol = "\\"; - if (symbol.equals(separator)) { - paths = genConfig.getPath().split("\\\\"); - } else { - paths = genConfig.getPath().split(File.separator); - } - StringBuilder api = new StringBuilder(); - for (String path : paths) { - api.append(path); - api.append(separator); - if ("src".equals(path)) { - api.append("api"); - break; - } - } - genConfig.setApiPath(api.toString()); - } - return genConfigRepository.save(genConfig); - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.service.impl; +// +//import cn.hutool.core.util.StrUtil; +//import lombok.RequiredArgsConstructor; +//import org.nl.modules.generator.domain.GenConfig; +//import org.nl.modules.generator.repository.GenConfigRepository; +//import org.nl.modules.generator.service.GenConfigService; +//import org.springframework.stereotype.Service; +// +//import java.io.File; +// +///** +// * @author Zheng Jie +// * @date 2019-01-14 +// */ +//@Service +//@RequiredArgsConstructor +//public class GenConfigServiceImpl implements GenConfigService { +// +// private final GenConfigRepository genConfigRepository; +// +// @Override +// public GenConfig find(String tableName) { +// GenConfig genConfig = genConfigRepository.findByTableName(tableName); +// if (genConfig == null) { +// return new GenConfig(tableName); +// } +// return genConfig; +// } +// +// @Override +// public GenConfig update(String tableName, GenConfig genConfig) { +// // 如果 api 路径为空,则自动生成路径 +// if (StrUtil.isEmpty(genConfig.getApiPath())) { +// String separator = File.separator; +// String[] paths; +// String symbol = "\\"; +// if (symbol.equals(separator)) { +// paths = genConfig.getPath().split("\\\\"); +// } else { +// paths = genConfig.getPath().split(File.separator); +// } +// StringBuilder api = new StringBuilder(); +// for (String path : paths) { +// api.append(path); +// api.append(separator); +// if ("src".equals(path)) { +// api.append("api"); +// break; +// } +// } +// genConfig.setApiPath(api.toString()); +// } +// return genConfigRepository.save(genConfig); +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java index 3fea2a993..2ca2614fa 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java @@ -1,203 +1,203 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.core.util.ZipUtil; -import lombok.RequiredArgsConstructor; -import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.FileUtil; -import org.nl.modules.common.utils.PageUtil; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.domain.vo.TableInfo; -import org.nl.modules.generator.repository.ColumnInfoRepository; -import org.nl.modules.generator.service.GeneratorService; -import org.nl.modules.generator.utils.GenUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * @author Zheng Jie - * @date 2019-01-02 - */ -@Service -@RequiredArgsConstructor -public class GeneratorServiceImpl implements GeneratorService { - private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class); - @PersistenceContext - private EntityManager em; - - private final ColumnInfoRepository columnInfoRepository; - - @Override - public Object getTables() { - // 使用预编译防止sql注入 - String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + - "where table_schema = (select database()) " + - "order by create_time desc"; - Query query = em.createNativeQuery(sql); - return query.getResultList(); - } - - @Override - public Object getTables(String name, int[] startEnd) { - // 使用预编译防止sql注入 - String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + - "where table_schema = (select database()) " + - "and table_name like ? order by create_time desc"; - Query query = em.createNativeQuery(sql); - query.setFirstResult(startEnd[0]); - query.setMaxResults(startEnd[1] - startEnd[0]); - query.setParameter(1, StrUtil.isNotEmpty(name) ? ("%" + name + "%") : "%%"); - List result = query.getResultList(); - List tableInfos = new ArrayList<>(); - for (Object obj : result) { - Object[] arr = (Object[]) obj; - tableInfos.add(new TableInfo(arr[0], arr[1], arr[2], arr[3], ObjectUtil.isNotEmpty(arr[4]) ? arr[4] : "-")); - } - Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())"); - Object totalElements = query1.getSingleResult(); - return PageUtil.toPage(tableInfos, totalElements); - } - - @Override - public List getColumns(String tableName) { - List columnInfos = columnInfoRepository.findByTableNameOrderByIdAsc(tableName); - if (CollectionUtil.isNotEmpty(columnInfos)) { - return columnInfos; - } else { - columnInfos = query(tableName); - return columnInfoRepository.saveAll(columnInfos); - } - } - - @Override - public List query(String tableName) { - // 使用预编译防止sql注入 - String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " + - "where table_name = ? and table_schema = (select database()) order by ordinal_position"; - Query query = em.createNativeQuery(sql); - query.setParameter(1, tableName); - List result = query.getResultList(); - List columnInfos = new ArrayList<>(); - for (Object obj : result) { - Object[] arr = (Object[]) obj; - columnInfos.add( - new ColumnInfo( - tableName, - arr[0].toString(), - "NO".equals(arr[1]), - arr[2].toString(), - ObjectUtil.isNotNull(arr[3]) ? arr[3].toString() : null, - ObjectUtil.isNotNull(arr[4]) ? arr[4].toString() : null, - ObjectUtil.isNotNull(arr[5]) ? arr[5].toString() : null) - ); - } - return columnInfos; - } - - @Override - public void sync(List columnInfos, List columnInfoList) { - // 第一种情况,数据库类字段改变或者新增字段 - for (ColumnInfo columnInfo : columnInfoList) { - // 根据字段名称查找 - List columns = columnInfos.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); - // 如果能找到,就修改部分可能被字段 - if (CollectionUtil.isNotEmpty(columns)) { - ColumnInfo column = columns.get(0); - column.setColumnType(columnInfo.getColumnType()); - column.setExtra(columnInfo.getExtra()); - column.setKeyType(columnInfo.getKeyType()); - if (StrUtil.isEmpty(column.getRemark())) { - column.setRemark(columnInfo.getRemark()); - } - columnInfoRepository.save(column); - } else { - // 如果找不到,则保存新字段信息 - columnInfoRepository.save(columnInfo); - } - } - // 第二种情况,数据库字段删除了 - for (ColumnInfo columnInfo : columnInfos) { - // 根据字段名称查找 - List columns = columnInfoList.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); - // 如果找不到,就代表字段被删除了,则需要删除该字段 - if (CollectionUtil.isEmpty(columns)) { - columnInfoRepository.delete(columnInfo); - } - } - } - - @Override - public void save(List columnInfos) { - columnInfoRepository.saveAll(columnInfos); - } - - @Override - public void generator(GenConfig genConfig, List columns) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - try { - GenUtil.generatorCode(columns, genConfig); - } catch (IOException e) { - log.error(e.getMessage(), e); - throw new BadRequestException("生成失败,请手动处理已生成的文件"); - } - } - - @Override - public ResponseEntity preview(GenConfig genConfig, List columns) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - List> genList = GenUtil.preview(columns, genConfig); - return new ResponseEntity<>(genList, HttpStatus.OK); - } - - @Override - public void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - try { - File file = new File(GenUtil.download(columns, genConfig)); - String zipPath = file.getPath() + ".zip"; - ZipUtil.zip(file.getPath(), zipPath); - FileUtil.downloadFile(request, response, new File(zipPath), true); - } catch (IOException e) { - throw new BadRequestException("打包失败"); - } - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.service.impl; +// +//import cn.hutool.core.collection.CollectionUtil; +//import cn.hutool.core.util.ObjectUtil; +//import cn.hutool.core.util.StrUtil; +//import cn.hutool.core.util.ZipUtil; +//import lombok.RequiredArgsConstructor; +//import org.nl.modules.common.exception.BadRequestException; +//import org.nl.modules.common.utils.FileUtil; +//import org.nl.modules.common.utils.PageUtil; +//import org.nl.modules.generator.domain.ColumnInfo; +//import org.nl.modules.generator.domain.GenConfig; +//import org.nl.modules.generator.domain.vo.TableInfo; +//import org.nl.modules.generator.repository.ColumnInfoRepository; +//import org.nl.modules.generator.service.GeneratorService; +//import org.nl.modules.generator.utils.GenUtil; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +//import org.springframework.http.HttpStatus; +//import org.springframework.http.ResponseEntity; +//import org.springframework.stereotype.Service; +// +//import javax.persistence.EntityManager; +//import javax.persistence.PersistenceContext; +//import javax.persistence.Query; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +//import java.io.File; +//import java.io.IOException; +//import java.util.ArrayList; +//import java.util.List; +//import java.util.Map; +//import java.util.stream.Collectors; +// +///** +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//@Service +//@RequiredArgsConstructor +//public class GeneratorServiceImpl implements GeneratorService { +// private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class); +// @PersistenceContext +// private EntityManager em; +// +// private final ColumnInfoRepository columnInfoRepository; +// +// @Override +// public Object getTables() { +// // 使用预编译防止sql注入 +// String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + +// "where table_schema = (select database()) " + +// "order by create_time desc"; +// Query query = em.createNativeQuery(sql); +// return query.getResultList(); +// } +// +// @Override +// public Object getTables(String name, int[] startEnd) { +// // 使用预编译防止sql注入 +// String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + +// "where table_schema = (select database()) " + +// "and table_name like ? order by create_time desc"; +// Query query = em.createNativeQuery(sql); +// query.setFirstResult(startEnd[0]); +// query.setMaxResults(startEnd[1] - startEnd[0]); +// query.setParameter(1, StrUtil.isNotEmpty(name) ? ("%" + name + "%") : "%%"); +// List result = query.getResultList(); +// List tableInfos = new ArrayList<>(); +// for (Object obj : result) { +// Object[] arr = (Object[]) obj; +// tableInfos.add(new TableInfo(arr[0], arr[1], arr[2], arr[3], ObjectUtil.isNotEmpty(arr[4]) ? arr[4] : "-")); +// } +// Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())"); +// Object totalElements = query1.getSingleResult(); +// return PageUtil.toPage(tableInfos, totalElements); +// } +// +// @Override +// public List getColumns(String tableName) { +// List columnInfos = columnInfoRepository.findByTableNameOrderByIdAsc(tableName); +// if (CollectionUtil.isNotEmpty(columnInfos)) { +// return columnInfos; +// } else { +// columnInfos = query(tableName); +// return columnInfoRepository.saveAll(columnInfos); +// } +// } +// +// @Override +// public List query(String tableName) { +// // 使用预编译防止sql注入 +// String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " + +// "where table_name = ? and table_schema = (select database()) order by ordinal_position"; +// Query query = em.createNativeQuery(sql); +// query.setParameter(1, tableName); +// List result = query.getResultList(); +// List columnInfos = new ArrayList<>(); +// for (Object obj : result) { +// Object[] arr = (Object[]) obj; +// columnInfos.add( +// new ColumnInfo( +// tableName, +// arr[0].toString(), +// "NO".equals(arr[1]), +// arr[2].toString(), +// ObjectUtil.isNotNull(arr[3]) ? arr[3].toString() : null, +// ObjectUtil.isNotNull(arr[4]) ? arr[4].toString() : null, +// ObjectUtil.isNotNull(arr[5]) ? arr[5].toString() : null) +// ); +// } +// return columnInfos; +// } +// +// @Override +// public void sync(List columnInfos, List columnInfoList) { +// // 第一种情况,数据库类字段改变或者新增字段 +// for (ColumnInfo columnInfo : columnInfoList) { +// // 根据字段名称查找 +// List columns = columnInfos.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); +// // 如果能找到,就修改部分可能被字段 +// if (CollectionUtil.isNotEmpty(columns)) { +// ColumnInfo column = columns.get(0); +// column.setColumnType(columnInfo.getColumnType()); +// column.setExtra(columnInfo.getExtra()); +// column.setKeyType(columnInfo.getKeyType()); +// if (StrUtil.isEmpty(column.getRemark())) { +// column.setRemark(columnInfo.getRemark()); +// } +// columnInfoRepository.save(column); +// } else { +// // 如果找不到,则保存新字段信息 +// columnInfoRepository.save(columnInfo); +// } +// } +// // 第二种情况,数据库字段删除了 +// for (ColumnInfo columnInfo : columnInfos) { +// // 根据字段名称查找 +// List columns = columnInfoList.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); +// // 如果找不到,就代表字段被删除了,则需要删除该字段 +// if (CollectionUtil.isEmpty(columns)) { +// columnInfoRepository.delete(columnInfo); +// } +// } +// } +// +// @Override +// public void save(List columnInfos) { +// columnInfoRepository.saveAll(columnInfos); +// } +// +// @Override +// public void generator(GenConfig genConfig, List columns) { +// if (genConfig.getId() == null) { +// throw new BadRequestException("请先配置生成器"); +// } +// try { +// GenUtil.generatorCode(columns, genConfig); +// } catch (IOException e) { +// log.error(e.getMessage(), e); +// throw new BadRequestException("生成失败,请手动处理已生成的文件"); +// } +// } +// +// @Override +// public ResponseEntity preview(GenConfig genConfig, List columns) { +// if (genConfig.getId() == null) { +// throw new BadRequestException("请先配置生成器"); +// } +// List> genList = GenUtil.preview(columns, genConfig); +// return new ResponseEntity<>(genList, HttpStatus.OK); +// } +// +// @Override +// public void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response) { +// if (genConfig.getId() == null) { +// throw new BadRequestException("请先配置生成器"); +// } +// try { +// File file = new File(GenUtil.download(columns, genConfig)); +// String zipPath = file.getPath() + ".zip"; +// ZipUtil.zip(file.getPath(), zipPath); +// FileUtil.downloadFile(request, response, new File(zipPath), true); +// } catch (IOException e) { +// throw new BadRequestException("打包失败"); +// } +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java index ff5a97192..908decf9d 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java @@ -1,56 +1,56 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.utils; - -import org.apache.commons.configuration.Configuration; -import org.apache.commons.configuration.ConfigurationException; -import org.apache.commons.configuration.PropertiesConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * sql字段转java - * - * @author Zheng Jie - * @date 2019-01-03 - */ -public class ColUtil { - private static final Logger log = LoggerFactory.getLogger(ColUtil.class); - - /** - * 转换mysql数据类型为java数据类型 - * - * @param type 数据库字段类型 - * @return String - */ - static String cloToJava(String type) { - Configuration config = getConfig(); - assert config != null; - return config.getString(type, "unknowType"); - } - - /** - * 获取配置信息 - */ - public static PropertiesConfiguration getConfig() { - try { - return new PropertiesConfiguration("generator.properties"); - } catch (ConfigurationException e) { - log.error(e.getMessage(), e); - } - return null; - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.utils; +// +//import org.apache.commons.configuration.Configuration; +//import org.apache.commons.configuration.ConfigurationException; +//import org.apache.commons.configuration.PropertiesConfiguration; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +///** +// * sql字段转java +// * +// * @author Zheng Jie +// * @date 2019-01-03 +// */ +//public class ColUtil { +// private static final Logger log = LoggerFactory.getLogger(ColUtil.class); +// +// /** +// * 转换mysql数据类型为java数据类型 +// * +// * @param type 数据库字段类型 +// * @return String +// */ +// static String cloToJava(String type) { +// Configuration config = getConfig(); +// assert config != null; +// return config.getString(type, "unknowType"); +// } +// +// /** +// * 获取配置信息 +// */ +// public static PropertiesConfiguration getConfig() { +// try { +// return new PropertiesConfiguration("generator.properties"); +// } catch (ConfigurationException e) { +// log.error(e.getMessage(), e); +// } +// return null; +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java index 37882ff58..6c2c28561 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java @@ -1,426 +1,426 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.utils; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.extra.template.*; -import lombok.extern.slf4j.Slf4j; -import org.nl.modules.common.utils.FileUtil; -import org.nl.modules.common.utils.StringUtils; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; -import org.springframework.util.ObjectUtils; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Writer; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.nl.modules.common.utils.FileUtil.SYS_TEM_DIR; - - -/** - * 代码生成 - * - * @author Zheng Jie - * @date 2019-01-02 - */ -@Slf4j -@SuppressWarnings({"unchecked", "all"}) -public class GenUtil { - - private static final String TIMESTAMP = "Timestamp"; - - private static final String BIGDECIMAL = "BigDecimal"; - - public static final String PK = "PRI"; - - public static final String EXTRA = "auto_increment"; - - /** - * 获取后端代码模板名称 - * - * @return List - */ - private static List getAdminTemplateNames() { - List templateNames = new ArrayList<>(); - // templateNames.add("Entity"); - templateNames.add("Dto"); - // templateNames.add("Mapper"); - templateNames.add("Controller"); - //templateNames.add("QueryCriteria"); - templateNames.add("Service"); - templateNames.add("ServiceImpl"); - // templateNames.add("Repository"); - return templateNames; - } - - /** - * 获取前端代码模板名称 - * - * @return List - */ - private static List getFrontTemplateNames() { - List templateNames = new ArrayList<>(); - templateNames.add("index"); - templateNames.add("api"); - return templateNames; - } - - public static List> preview(List columns, GenConfig genConfig) { - Map genMap = getGenMap(columns, genConfig); - List> genList = new ArrayList<>(); - // 获取后端模版 - List templates = getAdminTemplateNames(); - TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); - for (String templateName : templates) { - Map map = new HashMap<>(1); - Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); - map.put("content", template.render(genMap)); - map.put("name", templateName); - genList.add(map); - } - // 获取前端模版 - templates = getFrontTemplateNames(); - for (String templateName : templates) { - Map map = new HashMap<>(1); - Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); - map.put(templateName, template.render(genMap)); - map.put("content", template.render(genMap)); - map.put("name", templateName); - genList.add(map); - } - return genList; - } - - public static String download(List columns, GenConfig genConfig) throws IOException { - // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ - // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; - String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; - Map genMap = getGenMap(columns, genConfig); - TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); - // 生成后端代码 - List templates = getAdminTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); - String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); - assert filePath != null; - File file = new File(filePath); - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - // 生成前端代码 - templates = getFrontTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); - String path = tempPath + "nladmin-web" + File.separator; - String apiPath = path + "src" + File.separator + "api" + File.separator; - String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; - String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); - assert filePath != null; - File file = new File(filePath); - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - return tempPath; - } - - public static void generatorCode(List columnInfos, GenConfig genConfig) throws IOException { - Map genMap = getGenMap(columnInfos, genConfig); - TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); - // 生成后端代码 - List templates = getAdminTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); - String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), System.getProperty("user.dir")); - - assert filePath != null; - File file = new File(filePath); - - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - - // 生成前端代码 - templates = getFrontTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); - String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); - - assert filePath != null; - File file = new File(filePath); - - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - } - - // 获取模版数据 - private static Map getGenMap(List columnInfos, GenConfig genConfig) { - // 存储模版字段数据 - Map genMap = new HashMap<>(16); - // 接口别名 - genMap.put("apiAlias", genConfig.getApiAlias()); - // 包名称 - genMap.put("package", genConfig.getPack()); - // 模块名称 - genMap.put("moduleName", genConfig.getModuleName()); - // 作者 - genMap.put("author", genConfig.getAuthor()); - // 创建日期 - genMap.put("date", LocalDate.now().toString()); - // 表名 - genMap.put("tableName", genConfig.getTableName()); - // 大写开头的类名 - String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); - // 小写开头的类名 - String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); - // 判断是否去除表前缀 - if (StrUtil.isNotEmpty(genConfig.getPrefix())) { - className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); - changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); - } - // 保存类名 - genMap.put("className", className); - // 保存小写开头的类名 - genMap.put("changeClassName", changeClassName); - // 存在 Timestamp 字段 - genMap.put("hasTimestamp", false); - // 查询类中存在 Timestamp 字段 - genMap.put("queryHasTimestamp", false); - // 存在 BigDecimal 字段 - genMap.put("hasBigDecimal", false); - // 查询类中存在 BigDecimal 字段 - genMap.put("queryHasBigDecimal", false); - // 是否需要创建查询 - genMap.put("hasQuery", false); - // 自增主键 - genMap.put("auto", false); - // 存在字典 - genMap.put("hasDict", false); - // 存在日期注解 - genMap.put("hasDateAnnotation", false); - // 保存字段信息 - List> columns = new ArrayList<>(); - // 保存查询字段的信息 - List> queryColumns = new ArrayList<>(); - // 存储字典信息 - List dicts = new ArrayList<>(); - // 存储 between 信息 - List> betweens = new ArrayList<>(); - // 存储不为空的字段信息 - List> isNotNullColumns = new ArrayList<>(); - - for (ColumnInfo column : columnInfos) { - Map listMap = new HashMap<>(16); - // 字段描述 - listMap.put("remark", column.getRemark()); - // 字段类型 - listMap.put("columnKey", column.getKeyType()); - // 主键类型 - String colType = ColUtil.cloToJava(column.getColumnType()); - // 小写开头的字段名 - //String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); - String changeColumnName = column.getColumnName(); - // 大写开头的字段名 - String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); - if (PK.equals(column.getKeyType())) { - // 存储主键类型 - genMap.put("pkColumnType", colType); - // 存储小写开头的字段名 - genMap.put("pkChangeColName", changeColumnName); - // 存储大写开头的字段名 - genMap.put("pkCapitalColName", capitalColumnName); - } - // 是否存在 Timestamp 类型的字段 - if (TIMESTAMP.equals(colType)) { - genMap.put("hasTimestamp", true); - } - // 是否存在 BigDecimal 类型的字段 - if (BIGDECIMAL.equals(colType)) { - genMap.put("hasBigDecimal", true); - } - // 主键是否自增 - if (EXTRA.equals(column.getExtra())) { - genMap.put("auto", true); - } - // 主键存在字典 - if (StrUtil.isNotEmpty(column.getDictName())) { - genMap.put("hasDict", true); - dicts.add(column.getDictName()); - } - - // 存储字段类型 - listMap.put("columnType", colType); - // 存储字原始段名称 - listMap.put("columnName", column.getColumnName()); - // 不为空 - listMap.put("istNotNull", column.getNotNull()); - // 字段列表显示 - listMap.put("columnShow", column.getListShow()); - // 表单显示 - listMap.put("formShow", column.getFormShow()); - // 表单组件类型 - listMap.put("formType", StrUtil.isNotEmpty(column.getFormType()) ? column.getFormType() : "Input"); - // 小写开头的字段名称 - listMap.put("changeColumnName", changeColumnName); - //大写开头的字段名称 - listMap.put("capitalColumnName", capitalColumnName); - // 字典名称 - listMap.put("dictName", column.getDictName()); - // 日期注解 - listMap.put("dateAnnotation", column.getDateAnnotation()); - if (StrUtil.isNotEmpty(column.getDateAnnotation())) { - genMap.put("hasDateAnnotation", true); - } - // 添加非空字段信息 - if (column.getNotNull()) { - isNotNullColumns.add(listMap); - } - // 判断是否有查询,如有则把查询的字段set进columnQuery - if (!StrUtil.isEmpty(column.getQueryType())) { - // 查询类型 - listMap.put("queryType", column.getQueryType()); - // 是否存在查询 - genMap.put("hasQuery", true); - if (TIMESTAMP.equals(colType)) { - // 查询中存储 Timestamp 类型 - genMap.put("queryHasTimestamp", true); - } - if (BIGDECIMAL.equals(colType)) { - // 查询中存储 BigDecimal 类型 - genMap.put("queryHasBigDecimal", true); - } - if ("between".equalsIgnoreCase(column.getQueryType())) { - betweens.add(listMap); - } else { - // 添加到查询列表中 - queryColumns.add(listMap); - } - } - // 添加到字段列表中 - columns.add(listMap); - } - // 保存字段列表 - genMap.put("columns", columns); - // 保存查询列表 - genMap.put("queryColumns", queryColumns); - // 保存字段列表 - genMap.put("dicts", dicts); - // 保存查询列表 - genMap.put("betweens", betweens); - // 保存非空字段信息 - genMap.put("isNotNullColumns", isNotNullColumns); - return genMap; - } - - /** - * 定义后端文件路径以及名称 - */ - private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) { - String projectPath = rootPath + File.separator + genConfig.getModuleName(); - String packagePath = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; - if (!ObjectUtils.isEmpty(genConfig.getPack())) { - packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; - } - - if ("Entity".equals(templateName)) { - return packagePath + "domain" + File.separator + className + ".java"; - } - - if ("Controller".equals(templateName)) { - return packagePath + "rest" + File.separator + className + "Controller.java"; - } - - if ("Service".equals(templateName)) { - return packagePath + "service" + File.separator + className + "Service.java"; - } - - if ("ServiceImpl".equals(templateName)) { - return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; - } - - if ("Dto".equals(templateName)) { - return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; - } - - if ("QueryCriteria".equals(templateName)) { - return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java"; - } - - if ("Mapper".equals(templateName)) { - return packagePath + "service" + File.separator + "mapstruct" + File.separator + className + "Mapper.java"; - } - - if ("Repository".equals(templateName)) { - return packagePath + "repository" + File.separator + className + "Repository.java"; - } - - return null; - } - - /** - * 定义前端文件路径以及名称 - */ - private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { - - if ("api".equals(templateName)) { - return apiPath + File.separator + apiName + ".js"; - } - - if ("index".equals(templateName)) { - return path + File.separator + "index.vue"; - } - - return null; - } - - private static void genFile(File file, Template template, Map map) throws IOException { - // 生成目标文件 - Writer writer = null; - try { - FileUtil.touch(file); - writer = new FileWriter(file); - template.render(map, writer); - } catch (TemplateException | IOException e) { - throw new RuntimeException(e); - } finally { - assert writer != null; - writer.close(); - } - } -} +///* +// * Copyright 2019-2020 Zheng Jie +// * +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// */ +//package org.nl.modules.generator.utils; +// +//import cn.hutool.core.util.StrUtil; +//import cn.hutool.extra.template.*; +//import lombok.extern.slf4j.Slf4j; +//import org.nl.modules.common.utils.FileUtil; +//import org.nl.modules.common.utils.StringUtils; +//import org.nl.modules.generator.domain.ColumnInfo; +//import org.nl.modules.generator.domain.GenConfig; +//import org.springframework.util.ObjectUtils; +// +//import java.io.File; +//import java.io.FileWriter; +//import java.io.IOException; +//import java.io.Writer; +//import java.time.LocalDate; +//import java.util.ArrayList; +//import java.util.HashMap; +//import java.util.List; +//import java.util.Map; +// +//import static org.nl.modules.common.utils.FileUtil.SYS_TEM_DIR; +// +// +///** +// * 代码生成 +// * +// * @author Zheng Jie +// * @date 2019-01-02 +// */ +//@Slf4j +//@SuppressWarnings({"unchecked", "all"}) +//public class GenUtil { +// +// private static final String TIMESTAMP = "Timestamp"; +// +// private static final String BIGDECIMAL = "BigDecimal"; +// +// public static final String PK = "PRI"; +// +// public static final String EXTRA = "auto_increment"; +// +// /** +// * 获取后端代码模板名称 +// * +// * @return List +// */ +// private static List getAdminTemplateNames() { +// List templateNames = new ArrayList<>(); +// // templateNames.add("Entity"); +// templateNames.add("Dto"); +// // templateNames.add("Mapper"); +// templateNames.add("Controller"); +// //templateNames.add("QueryCriteria"); +// templateNames.add("Service"); +// templateNames.add("ServiceImpl"); +// // templateNames.add("Repository"); +// return templateNames; +// } +// +// /** +// * 获取前端代码模板名称 +// * +// * @return List +// */ +// private static List getFrontTemplateNames() { +// List templateNames = new ArrayList<>(); +// templateNames.add("index"); +// templateNames.add("api"); +// return templateNames; +// } +// +// public static List> preview(List columns, GenConfig genConfig) { +// Map genMap = getGenMap(columns, genConfig); +// List> genList = new ArrayList<>(); +// // 获取后端模版 +// List templates = getAdminTemplateNames(); +// TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); +// for (String templateName : templates) { +// Map map = new HashMap<>(1); +// Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); +// map.put("content", template.render(genMap)); +// map.put("name", templateName); +// genList.add(map); +// } +// // 获取前端模版 +// templates = getFrontTemplateNames(); +// for (String templateName : templates) { +// Map map = new HashMap<>(1); +// Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); +// map.put(templateName, template.render(genMap)); +// map.put("content", template.render(genMap)); +// map.put("name", templateName); +// genList.add(map); +// } +// return genList; +// } +// +// public static String download(List columns, GenConfig genConfig) throws IOException { +// // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ +// // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; +// String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; +// Map genMap = getGenMap(columns, genConfig); +// TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); +// // 生成后端代码 +// List templates = getAdminTemplateNames(); +// for (String templateName : templates) { +// Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); +// String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); +// assert filePath != null; +// File file = new File(filePath); +// // 如果非覆盖生成 +// if (!genConfig.getCover() && FileUtil.exist(file)) { +// continue; +// } +// // 生成代码 +// genFile(file, template, genMap); +// } +// // 生成前端代码 +// templates = getFrontTemplateNames(); +// for (String templateName : templates) { +// Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); +// String path = tempPath + "nladmin-web" + File.separator; +// String apiPath = path + "src" + File.separator + "api" + File.separator; +// String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; +// String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); +// assert filePath != null; +// File file = new File(filePath); +// // 如果非覆盖生成 +// if (!genConfig.getCover() && FileUtil.exist(file)) { +// continue; +// } +// // 生成代码 +// genFile(file, template, genMap); +// } +// return tempPath; +// } +// +// public static void generatorCode(List columnInfos, GenConfig genConfig) throws IOException { +// Map genMap = getGenMap(columnInfos, genConfig); +// TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); +// // 生成后端代码 +// List templates = getAdminTemplateNames(); +// for (String templateName : templates) { +// Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); +// String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), System.getProperty("user.dir")); +// +// assert filePath != null; +// File file = new File(filePath); +// +// // 如果非覆盖生成 +// if (!genConfig.getCover() && FileUtil.exist(file)) { +// continue; +// } +// // 生成代码 +// genFile(file, template, genMap); +// } +// +// // 生成前端代码 +// templates = getFrontTemplateNames(); +// for (String templateName : templates) { +// Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); +// String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); +// +// assert filePath != null; +// File file = new File(filePath); +// +// // 如果非覆盖生成 +// if (!genConfig.getCover() && FileUtil.exist(file)) { +// continue; +// } +// // 生成代码 +// genFile(file, template, genMap); +// } +// } +// +// // 获取模版数据 +// private static Map getGenMap(List columnInfos, GenConfig genConfig) { +// // 存储模版字段数据 +// Map genMap = new HashMap<>(16); +// // 接口别名 +// genMap.put("apiAlias", genConfig.getApiAlias()); +// // 包名称 +// genMap.put("package", genConfig.getPack()); +// // 模块名称 +// genMap.put("moduleName", genConfig.getModuleName()); +// // 作者 +// genMap.put("author", genConfig.getAuthor()); +// // 创建日期 +// genMap.put("date", LocalDate.now().toString()); +// // 表名 +// genMap.put("tableName", genConfig.getTableName()); +// // 大写开头的类名 +// String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); +// // 小写开头的类名 +// String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); +// // 判断是否去除表前缀 +// if (StrUtil.isNotEmpty(genConfig.getPrefix())) { +// className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); +// changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); +// } +// // 保存类名 +// genMap.put("className", className); +// // 保存小写开头的类名 +// genMap.put("changeClassName", changeClassName); +// // 存在 Timestamp 字段 +// genMap.put("hasTimestamp", false); +// // 查询类中存在 Timestamp 字段 +// genMap.put("queryHasTimestamp", false); +// // 存在 BigDecimal 字段 +// genMap.put("hasBigDecimal", false); +// // 查询类中存在 BigDecimal 字段 +// genMap.put("queryHasBigDecimal", false); +// // 是否需要创建查询 +// genMap.put("hasQuery", false); +// // 自增主键 +// genMap.put("auto", false); +// // 存在字典 +// genMap.put("hasDict", false); +// // 存在日期注解 +// genMap.put("hasDateAnnotation", false); +// // 保存字段信息 +// List> columns = new ArrayList<>(); +// // 保存查询字段的信息 +// List> queryColumns = new ArrayList<>(); +// // 存储字典信息 +// List dicts = new ArrayList<>(); +// // 存储 between 信息 +// List> betweens = new ArrayList<>(); +// // 存储不为空的字段信息 +// List> isNotNullColumns = new ArrayList<>(); +// +// for (ColumnInfo column : columnInfos) { +// Map listMap = new HashMap<>(16); +// // 字段描述 +// listMap.put("remark", column.getRemark()); +// // 字段类型 +// listMap.put("columnKey", column.getKeyType()); +// // 主键类型 +// String colType = ColUtil.cloToJava(column.getColumnType()); +// // 小写开头的字段名 +// //String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); +// String changeColumnName = column.getColumnName(); +// // 大写开头的字段名 +// String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); +// if (PK.equals(column.getKeyType())) { +// // 存储主键类型 +// genMap.put("pkColumnType", colType); +// // 存储小写开头的字段名 +// genMap.put("pkChangeColName", changeColumnName); +// // 存储大写开头的字段名 +// genMap.put("pkCapitalColName", capitalColumnName); +// } +// // 是否存在 Timestamp 类型的字段 +// if (TIMESTAMP.equals(colType)) { +// genMap.put("hasTimestamp", true); +// } +// // 是否存在 BigDecimal 类型的字段 +// if (BIGDECIMAL.equals(colType)) { +// genMap.put("hasBigDecimal", true); +// } +// // 主键是否自增 +// if (EXTRA.equals(column.getExtra())) { +// genMap.put("auto", true); +// } +// // 主键存在字典 +// if (StrUtil.isNotEmpty(column.getDictName())) { +// genMap.put("hasDict", true); +// dicts.add(column.getDictName()); +// } +// +// // 存储字段类型 +// listMap.put("columnType", colType); +// // 存储字原始段名称 +// listMap.put("columnName", column.getColumnName()); +// // 不为空 +// listMap.put("istNotNull", column.getNotNull()); +// // 字段列表显示 +// listMap.put("columnShow", column.getListShow()); +// // 表单显示 +// listMap.put("formShow", column.getFormShow()); +// // 表单组件类型 +// listMap.put("formType", StrUtil.isNotEmpty(column.getFormType()) ? column.getFormType() : "Input"); +// // 小写开头的字段名称 +// listMap.put("changeColumnName", changeColumnName); +// //大写开头的字段名称 +// listMap.put("capitalColumnName", capitalColumnName); +// // 字典名称 +// listMap.put("dictName", column.getDictName()); +// // 日期注解 +// listMap.put("dateAnnotation", column.getDateAnnotation()); +// if (StrUtil.isNotEmpty(column.getDateAnnotation())) { +// genMap.put("hasDateAnnotation", true); +// } +// // 添加非空字段信息 +// if (column.getNotNull()) { +// isNotNullColumns.add(listMap); +// } +// // 判断是否有查询,如有则把查询的字段set进columnQuery +// if (!StrUtil.isEmpty(column.getQueryType())) { +// // 查询类型 +// listMap.put("queryType", column.getQueryType()); +// // 是否存在查询 +// genMap.put("hasQuery", true); +// if (TIMESTAMP.equals(colType)) { +// // 查询中存储 Timestamp 类型 +// genMap.put("queryHasTimestamp", true); +// } +// if (BIGDECIMAL.equals(colType)) { +// // 查询中存储 BigDecimal 类型 +// genMap.put("queryHasBigDecimal", true); +// } +// if ("between".equalsIgnoreCase(column.getQueryType())) { +// betweens.add(listMap); +// } else { +// // 添加到查询列表中 +// queryColumns.add(listMap); +// } +// } +// // 添加到字段列表中 +// columns.add(listMap); +// } +// // 保存字段列表 +// genMap.put("columns", columns); +// // 保存查询列表 +// genMap.put("queryColumns", queryColumns); +// // 保存字段列表 +// genMap.put("dicts", dicts); +// // 保存查询列表 +// genMap.put("betweens", betweens); +// // 保存非空字段信息 +// genMap.put("isNotNullColumns", isNotNullColumns); +// return genMap; +// } +// +// /** +// * 定义后端文件路径以及名称 +// */ +// private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) { +// String projectPath = rootPath + File.separator + genConfig.getModuleName(); +// String packagePath = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; +// if (!ObjectUtils.isEmpty(genConfig.getPack())) { +// packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; +// } +// +// if ("Entity".equals(templateName)) { +// return packagePath + "domain" + File.separator + className + ".java"; +// } +// +// if ("Controller".equals(templateName)) { +// return packagePath + "rest" + File.separator + className + "Controller.java"; +// } +// +// if ("Service".equals(templateName)) { +// return packagePath + "service" + File.separator + className + "Service.java"; +// } +// +// if ("ServiceImpl".equals(templateName)) { +// return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; +// } +// +// if ("Dto".equals(templateName)) { +// return packagePath + "service" + File.separator + "dto" + File.separator + className + "Dto.java"; +// } +// +// if ("QueryCriteria".equals(templateName)) { +// return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java"; +// } +// +// if ("Mapper".equals(templateName)) { +// return packagePath + "service" + File.separator + "mapstruct" + File.separator + className + "Mapper.java"; +// } +// +// if ("Repository".equals(templateName)) { +// return packagePath + "repository" + File.separator + className + "Repository.java"; +// } +// +// return null; +// } +// +// /** +// * 定义前端文件路径以及名称 +// */ +// private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { +// +// if ("api".equals(templateName)) { +// return apiPath + File.separator + apiName + ".js"; +// } +// +// if ("index".equals(templateName)) { +// return path + File.separator + "index.vue"; +// } +// +// return null; +// } +// +// private static void genFile(File file, Template template, Map map) throws IOException { +// // 生成目标文件 +// Writer writer = null; +// try { +// FileUtil.touch(file); +// writer = new FileWriter(file); +// template.render(map, writer); +// } catch (TemplateException | IOException e) { +// throw new RuntimeException(e); +// } finally { +// assert writer != null; +// writer.close(); +// } +// } +//} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java b/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java new file mode 100644 index 000000000..bffd59a96 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGenConfigController.java @@ -0,0 +1,42 @@ +package org.nl.system.controller.generator; + + +import cn.dev33.satoken.annotation.SaIgnore; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +/** + *

+ * 代码生成配置表 前端控制器 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@SaIgnore +@RestController + +@RequestMapping("api/genConfig") +public class CodeGenConfigController { + + @Autowired + private ICodeGenConfigService genConfigService; + + + @GetMapping(value = "/{tableName}") + public ResponseEntity query(@PathVariable String tableName) { + return new ResponseEntity<>(genConfigService.findByTableName(tableName), HttpStatus.OK); + } + + + @PutMapping + public ResponseEntity update(@Validated @RequestBody CodeGenConfig genConfig) { + return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig), HttpStatus.OK); + } +} + diff --git a/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java b/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java new file mode 100644 index 000000000..751c474c1 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/controller/generator/CodeGeneratorController.java @@ -0,0 +1,93 @@ +package org.nl.system.controller.generator; + +import cn.dev33.satoken.annotation.SaIgnore; +import org.nl.common.TableDataInfo; +import org.nl.common.domain.query.PageQuery; +import org.nl.modules.common.exception.BadRequestException; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.ICodeGeneratorService; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + *

+ * 列的数据信息表 前端控制器 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@SaIgnore +@RestController +@RequestMapping("/api/generator") + +public class CodeGeneratorController { + @Autowired + private ICodeGeneratorService generatorService; + @Autowired + private ICodeGenConfigService genConfigService; + + @Value("${generator.enabled}") + private Boolean generatorEnabled; + + + @GetMapping(value = "/tables") + public ResponseEntity queryTables(@RequestParam(defaultValue = "") String name, PageQuery pageable) { + return new ResponseEntity<>(TableDataInfo.build(generatorService.getTables(name, pageable)), HttpStatus.OK); + } + + + @GetMapping(value = "/columns") + public ResponseEntity queryColumns(@RequestParam String tableName) { + return new ResponseEntity<>(TableDataInfo.build(generatorService.getColumns(tableName)), HttpStatus.OK); + } + + + @PutMapping + public ResponseEntity save(@RequestBody List columnInfos) { + generatorService.updateBatchById(columnInfos); + return new ResponseEntity<>(HttpStatus.OK); + } + + + @PostMapping(value = "sync") + public ResponseEntity sync(@RequestBody List tables) { + for (String table : tables) { + generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); + } + return new ResponseEntity<>(HttpStatus.OK); + } + + + @PostMapping(value = "/{tableName}/{type}") + public ResponseEntity generator(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) { + if (!generatorEnabled && type == 0) { + throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); + } + switch (type) { + // 生成代码 + case 0: + generatorService.generator(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName)); + break; + // 预览 + case 1: + return generatorService.preview(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName)); + // 打包 + case 2: + generatorService.download(genConfigService.findByTableName(tableName), generatorService.getColumns(tableName), request, response); + break; + default: + throw new BadRequestException("没有这个选项"); + } + return new ResponseEntity<>(HttpStatus.OK); + } +} + diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java new file mode 100644 index 000000000..7710bf3f9 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGenConfigService.java @@ -0,0 +1,32 @@ +package org.nl.system.service.generator; + +import com.baomidou.mybatisplus.extension.service.IService; +import org.nl.system.service.generator.dao.CodeGenConfig; + +/** + *

+ * 代码生成配置表 服务类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface ICodeGenConfigService extends IService { + + /** + * 根据表名查找 + * + * @param tableName + * @return + */ + CodeGenConfig findByTableName(String tableName); + + /** + * 根据表名更新 + * + * @param tableName + * @param genConfig + * @return + */ + CodeGenConfig update(String tableName, CodeGenConfig genConfig); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java new file mode 100644 index 000000000..7ada3d817 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/ICodeGeneratorService.java @@ -0,0 +1,86 @@ +package org.nl.system.service.generator; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.IService; +import org.nl.common.domain.query.PageQuery; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dto.TablesInfo; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Async; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + *

+ * 列的数据信息表 服务类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface ICodeGeneratorService extends IService { + + /** + * 获得所有的表格信息 + * + * @param name + * @param pageQuery + * @return + */ + IPage getTables(String name, PageQuery pageQuery); + + /** + * 得到数据表的元数据 + * + * @param tableName 表名 + * @return / + */ + IPage getColumns(String tableName); + + /** + * 根据表名查询表字段 + * + * @param tableName + * @return + */ + List query(String tableName); + + /** + * 同步表数据 + * + * @param columnInfos / + * @param columnInfoList / + */ + @Async + void sync(IPage columnInfos, List columnInfoList); + + /** + * 预览代码 + * + * @param byTableName + * @param columns + * @return + */ + ResponseEntity preview(CodeGenConfig byTableName, IPage columns); + + /** + * 打包下载 + * + * @param genConfig 配置信息 + * @param columnsPage 字段信息分页数据 + * @param request / + * @param response / + */ + void download(CodeGenConfig genConfig, IPage columnsPage, HttpServletRequest request, HttpServletResponse response); + + /** + * 代码生成 + * + * @param genConfig 配置信息 + * @param columnsPage 字段信息分页数据 + */ + void generator(CodeGenConfig genConfig, IPage columnsPage); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java new file mode 100644 index 000000000..bc94706ee --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeColumnConfig.java @@ -0,0 +1,99 @@ +package org.nl.system.service.generator.dao; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import org.nl.common.utils.GenUtil; +import org.nl.system.service.generator.dto.ColumnInfo; + +import java.io.Serializable; + +/** + *

+ * 列的数据信息表 + *

+ * + * @author generator + * @since 2023-05-03 + */ +@Data +@TableName("code_column_config") +public class CodeColumnConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + /** + * 标识 + */ + @TableId(value = "column_id", type = IdType.ASSIGN_ID) + private String columnId; + + @TableField(value = "table_name") + private String tableName; + + @TableField(value = "column_name") + private String columnName; + + @TableField(value = "column_type") + private String columnType; + + @TableField(value = "key_type") + private String keyType; + + @TableField(value = "extra") + private String extra; + + @TableField(value = "remark") + private String remark; + + @TableField(value = "not_null") + private Boolean notNull; + + @TableField(value = "list_show") + private Boolean listShow; + + @TableField(value = "form_show") + private Boolean formShow; + + @TableField(value = "form_type") + private String formType; + + @TableField(value = "query_type") + private String queryType; + + @TableField(value = "dict_name") + private String dictName; + + @TableField(value = "date_annotation") + private String dateAnnotation; + + /** + * 创建默认的实体 + * + * @param tableName + * @param config + * @return + */ + public static CodeColumnConfig createDefault(String tableName, ColumnInfo config) { + CodeColumnConfig columnConfig = new CodeColumnConfig(); + columnConfig.setColumnId(IdUtil.getSnowflake(1, 1).nextIdStr()); + columnConfig.setTableName(tableName); + columnConfig.setColumnName(config.getColumnName()); + columnConfig.setColumnType(config.getColumnType()); + columnConfig.setKeyType(config.getKeyType()); + columnConfig.setExtra(config.getExtra()); + columnConfig.setNotNull((ObjectUtil.isNotEmpty(config.getKeyType()) + && ObjectUtil.isNotEmpty(config.getExtra()) + && GenUtil.PK.equalsIgnoreCase(config.getKeyType()) + && GenUtil.EXTRA.equalsIgnoreCase(config.getExtra())) + ? false : ObjectUtil.isNotEmpty(config.getNotNull()) ? config.getNotNull() : false); + columnConfig.setRemark(ObjectUtil.isNotEmpty(config.getRemark()) ? config.getRemark() : null); + columnConfig.setListShow(true); + columnConfig.setFormShow(true); + return columnConfig; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java new file mode 100644 index 000000000..c3e18f4a6 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/CodeGenConfig.java @@ -0,0 +1,88 @@ +package org.nl.system.service.generator.dao; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + *

+ * 代码生成配置表 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Data +@NoArgsConstructor +@EqualsAndHashCode(callSuper = false) +@TableName("code_gen_config") +public class CodeGenConfig implements Serializable { + + private static final long serialVersionUID = 1L; + + public CodeGenConfig(String tableName) { + this.tableName = tableName; + } + + /** + * ID + */ + @TableId(value = "config_id") + private String configId; + + /** + * 表名 + */ + @TableField(value = "table_name") + private String tableName; + + /** + * 作者 + */ + private String author; + + /** + * 是否覆盖 + */ + private Boolean cover; + + /** + * 模块名称 + */ + @TableField(value = "module_name") + private String moduleName; + + /** + * 包名 + */ + private String pack; + + /** + * 路径 + */ + private String path; + + /** + * api路径 + */ + @TableField(value = "api_path") + private String apiPath; + + /** + * 表前缀 + */ + private String prefix; + + /** + * 接口名称 + */ + @TableField(value = "api_alias") + private String apiAlias; + + +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java new file mode 100644 index 000000000..2008a91fb --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.java @@ -0,0 +1,43 @@ +package org.nl.system.service.generator.dao.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dto.ColumnInfo; +import org.nl.system.service.generator.dto.TablesInfo; + +import java.util.List; + +/** + *

+ * 列的数据信息表 Mapper 接口 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +public interface CodeColumnConfigMapper extends BaseMapper { + + /** + * 分页查找 + * + * @param name 表名 + * @return 表信息 + */ + List getTables(String name, int pageSize, int offset); + + /** + * 分页查询的总数 + * + * @param name 表名 + * @return 表信息 + */ + long getTablesTotal(String name); + + /** + * 获取 + * + * @param tableName 表名 + * @return 列数据 + */ + List getTablesByTableName(String tableName); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml new file mode 100644 index 000000000..ef3e459d1 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeColumnConfigMapper.xml @@ -0,0 +1,46 @@ + + + + + + + + diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java new file mode 100644 index 000000000..10b0b405c --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.java @@ -0,0 +1,16 @@ +package org.nl.system.service.generator.dao.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.nl.system.service.generator.dao.CodeGenConfig; + +/** + *

+ * 代码生成配置表 Mapper 接口 + *

+ * + * @author generator + * @since 2023-05-03 + */ +public interface CodeGenConfigMapper extends BaseMapper { + +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml new file mode 100644 index 000000000..72ca44ceb --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dao/mapper/CodeGenConfigMapper.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java new file mode 100644 index 000000000..dc4453d67 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/ColumnInfo.java @@ -0,0 +1,49 @@ +package org.nl.system.service.generator.dto; + +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.Data; + +/** + * @Author: lyd + * @Description: 字段信息 + * @Date: 2023/5/3 + */ +@Data +public class ColumnInfo { + + @TableField(value = "column_name") + private String columnName; + + @TableField(value = "column_type") + private String columnType; + + @TableField(value = "key_type") + private String keyType; + + + private String extra; + + + private String remark; + + @TableField(value = "not_null") + private Boolean notNull; + + @TableField(value = "list_show") + private Boolean listShow; + + @TableField(value = "form_show") + private Boolean formShow; + + @TableField(value = "form_type") + private String formType; + + @TableField(value = "query_type") + private String queryType; + + @TableField(value = "dict_name") + private String dictName; + + @TableField(value = "date_annotation") + private String dateAnnotation; +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java new file mode 100644 index 000000000..c081b87ae --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/dto/TablesInfo.java @@ -0,0 +1,43 @@ +package org.nl.system.service.generator.dto; + +import com.baomidou.mybatisplus.annotation.TableField; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @Author: lyd + * @Description: 表的数据信息 + * @Date: 2023/5/3 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class TablesInfo { + /** + * 表名 + */ + @TableField(value = "table_name") + private String tableName; + + /** + * 创建时间 + */ + @TableField(value = "create_time") + private String createTime; + + /** + * 引擎 + */ + private String ENGINE; + + /** + * 字符序 + */ + private String coding; + + /** + * 注释 + */ + private String remark; +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java new file mode 100644 index 000000000..40a1f8ac5 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGenConfigServiceImpl.java @@ -0,0 +1,71 @@ +package org.nl.system.service.generator.impl; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.system.service.generator.ICodeGenConfigService; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dao.mapper.CodeGenConfigMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.io.File; + +/** + *

+ * 代码生成配置表 服务实现类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Service +public class CodeGenConfigServiceImpl extends ServiceImpl implements ICodeGenConfigService { + + @Autowired + private CodeGenConfigMapper codeGenConfigMapper; + + @Override + public CodeGenConfig findByTableName(String tableName) { + CodeGenConfig codeGenConfig = codeGenConfigMapper.selectOne(new LambdaQueryWrapper() + .eq(CodeGenConfig::getTableName, tableName)); + if (ObjectUtil.isEmpty(codeGenConfig)) { + return new CodeGenConfig(tableName); + } + return codeGenConfig; + } + + @Override + public CodeGenConfig update(String tableName, CodeGenConfig genConfig) { + // 如果 api 路径为空,则自动生成路径 + if (StrUtil.isEmpty(genConfig.getApiPath())) { + String separator = File.separator; + String[] paths; + String symbol = "\\"; + if (symbol.equals(separator)) { + paths = genConfig.getPath().split("\\\\"); + } else { + paths = genConfig.getPath().split(File.separator); + } + StringBuilder api = new StringBuilder(); + for (String path : paths) { + api.append(path); + api.append(separator); + if ("src".equals(path)) { + api.append("api"); + break; + } + } + genConfig.setApiPath(api.toString()); + } + if (ObjectUtil.isNotEmpty(genConfig.getConfigId())) { + codeGenConfigMapper.updateById(genConfig); + } else { + genConfig.setConfigId(IdUtil.getSnowflake(1, 1).nextIdStr()); + codeGenConfigMapper.insert(genConfig); + } + return genConfig; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java new file mode 100644 index 000000000..1fdc4b79e --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/system/service/generator/impl/CodeGeneratorServiceImpl.java @@ -0,0 +1,162 @@ +package org.nl.system.service.generator.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.ZipUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.utils.GenUtil; +import org.nl.modules.common.exception.BadRequestException; +import org.nl.modules.common.utils.FileUtil; +import org.nl.system.service.generator.ICodeGeneratorService; +import org.nl.system.service.generator.dao.CodeColumnConfig; +import org.nl.system.service.generator.dao.CodeGenConfig; +import org.nl.system.service.generator.dao.mapper.CodeColumnConfigMapper; +import org.nl.system.service.generator.dto.ColumnInfo; +import org.nl.system.service.generator.dto.TablesInfo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + *

+ * 列的数据信息表 服务实现类 + *

+ * + * @author lyd + * @since 2023-05-03 + */ +@Service +public class CodeGeneratorServiceImpl extends ServiceImpl implements ICodeGeneratorService { + + @Autowired + private CodeColumnConfigMapper columnConfigMapper; + + @Override + public IPage getTables(String name, PageQuery pageQuery) { + IPage pages = new Page<>(); + int page = pageQuery.getPage(); + int pageSize = pageQuery.getSize(); + int offset = page * pageSize; + List tableInfos = columnConfigMapper.getTables(name, pageSize, offset); + long num = columnConfigMapper.getTablesTotal(name); + pages.setRecords(tableInfos); + pages.setCurrent(page + 1); + pages.setSize(pageSize); + pages.setTotal(num); + return pages; + } + + @Override + public IPage getColumns(String tableName) { + IPage pages = new Page<>(); + // 查找行列数据表 + List codeColumnConfigs = columnConfigMapper + .selectList(new LambdaQueryWrapper() + .eq(CodeColumnConfig::getTableName, tableName)); + if (ObjectUtil.isEmpty(codeColumnConfigs)) { + // 为空查找全新的数据 + codeColumnConfigs = query(tableName); + // 保存 + this.saveBatch(codeColumnConfigs); + } + pages.setRecords(codeColumnConfigs); + return pages; + } + + @Override + public List query(String tableName) { + List columnConfigList = columnConfigMapper.getTablesByTableName(tableName); + // 设置默认值 + List columnInfos = columnConfigList.stream() + .map(config -> CodeColumnConfig.createDefault(tableName, config)) + .collect(Collectors.toList()); + return columnInfos; + } + + @Override + public void sync(IPage columnInfos, List columnInfoList) { + List records = columnInfos.getRecords(); + // 第一种情况,数据库类字段改变或者新增字段 + for (CodeColumnConfig columnInfo : columnInfoList) { + // 根据字段名称查找 + List columns = records.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); + // 如果能找到,就修改部分可能被字段 + if (CollectionUtil.isNotEmpty(columns)) { + CodeColumnConfig column = columns.get(0); + column.setColumnType(columnInfo.getColumnType()); + column.setExtra(columnInfo.getExtra()); + column.setKeyType(columnInfo.getKeyType()); + if (StrUtil.isEmpty(column.getRemark())) { + column.setRemark(columnInfo.getRemark()); + } + columnConfigMapper.updateById(column); + } else { + // 如果找不到,则保存新字段信息 + columnConfigMapper.insert(columnInfo); + } + } + // 第二种情况,数据库字段删除了 + for (CodeColumnConfig columnInfo : records) { + // 根据字段名称查找 + List columns = columnInfoList.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); + // 如果找不到,就代表字段被删除了,则需要删除该字段 + if (CollectionUtil.isEmpty(columns)) { + columnConfigMapper.deleteById(columnInfo.getColumnId()); + } + } + } + + @Override + public ResponseEntity preview(CodeGenConfig genConfig, IPage columns) { + List columnsRecords = columns.getRecords(); + if (genConfig.getConfigId() == null) { + throw new BadRequestException("请先配置生成器"); + } + List> genList = GenUtil.preview(columnsRecords, genConfig); + return new ResponseEntity<>(genList, HttpStatus.OK); + } + + @Override + public void download(CodeGenConfig genConfig, IPage columnsPage, HttpServletRequest request, HttpServletResponse response) { + List columns = columnsPage.getRecords(); + if (genConfig.getConfigId() == null) { + throw new BadRequestException("请先配置生成器"); + } + try { + File file = new File(GenUtil.download(columns, genConfig)); + String zipPath = file.getPath() + ".zip"; + ZipUtil.zip(file.getPath(), zipPath); + FileUtil.downloadFile(request, response, new File(zipPath), true); + } catch (IOException e) { + throw new BadRequestException("打包失败"); + } + } + + @Override + public void generator(CodeGenConfig genConfig, IPage columnsPage) { + List columns = columnsPage.getRecords(); + if (genConfig.getConfigId() == null) { + throw new BadRequestException("请先配置生成器"); + } + try { + GenUtil.generatorCode(columns, genConfig); + } catch (IOException e) { + log.error(e.getMessage(), e); + throw new BadRequestException("生成失败,请手动处理已生成的文件"); + } + } +} diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl index ec934f094..2b9e995e0 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/Controller.ftl @@ -1,64 +1,60 @@ +package ${package}.controller; -package ${package}.rest; - - -import org.springframework.data.domain.Pageable; -import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.nl.common.TableDataInfo; +import org.nl.common.domain.query.PageQuery; import org.nl.modules.logging.annotation.Log; +import ${package}.service.I${className}Service; +import ${package}.service.dao.${className}; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import cn.dev33.satoken.annotation.SaCheckPermission; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.Map; -import lombok.extern.slf4j.Slf4j; - +import java.util.Set; /** * @author ${author} * @date ${date} **/ -@RestController -@RequiredArgsConstructor - -@RequestMapping("/api/${changeClassName}") @Slf4j +@RestController +@RequestMapping("/api/${changeClassName}") public class ${className}Controller { - private final ${className}Service ${changeClassName}Service; + @Autowired + private I${className}Service ${changeClassName}Service; @GetMapping @Log("查询${apiAlias}") - //@SaCheckPermission("@el.check('${changeClassName}:list')") - public ResponseEntity query(@RequestParam Map whereJson, Pageable page){ - return new ResponseEntity<>(${changeClassName}Service.queryAll(whereJson,page),HttpStatus.OK); + public ResponseEntity query(@RequestParam Map whereJson, PageQuery page){ + return new ResponseEntity<>(TableDataInfo.build(${changeClassName}Service.queryAll(whereJson,page)),HttpStatus.OK); } @PostMapping @Log("新增${apiAlias}") - //@SaCheckPermission("@el.check('${changeClassName}:add')") - public ResponseEntity create(@Validated @RequestBody ${className}Dto dto){ - ${changeClassName}Service.create(dto); + public ResponseEntity + create(@Validated @RequestBody ${className} entity){ + ${changeClassName}Service.create(entity); return new ResponseEntity<>(HttpStatus.CREATED); } @PutMapping @Log("修改${apiAlias}") - //@SaCheckPermission("@el.check('${changeClassName}:edit')") - public ResponseEntity update(@Validated @RequestBody ${className}Dto dto){ - ${changeClassName}Service.update(dto); + public ResponseEntity update(@Validated @RequestBody ${className} entity){ + ${changeClassName}Service.update(entity); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Log("删除${apiAlias}") - //@SaCheckPermission("@el.check('${changeClassName}:del')") @DeleteMapping - public ResponseEntity delete(@RequestBody ${pkColumnType}[] ids) { - ${changeClassName}Service.deleteAll(ids); - return new ResponseEntity<>(HttpStatus.OK); + public ResponseEntity delete(@RequestBody Set ids) { + ${changeClassName}Service.deleteAll(ids); + return new ResponseEntity<>(HttpStatus.OK); } } diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/Dto.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/Dto.ftl index edfadda24..a17898bdc 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/Dto.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/Dto.ftl @@ -1,17 +1,16 @@ package ${package}.service.dto; -import lombok.Data; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; <#if hasTimestamp> - import java.sql.Timestamp; +import java.sql.Timestamp; <#if hasBigDecimal> - import java.math.BigDecimal; +import java.math.BigDecimal; +import lombok.Data; +import lombok.Builder; import java.io.Serializable; -<#if !auto && pkColumnType = 'Long'> - import com.fasterxml.jackson.databind.annotation.JsonSerialize; - import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; - /** * @description / @@ -19,20 +18,21 @@ import java.io.Serializable; * @date ${date} **/ @Data +@Builder public class ${className}Dto implements Serializable { <#if columns??> <#list columns as column> - <#if column.remark != ''> - /** ${column.remark} */ - - <#if column.columnKey = 'PRI'> - <#if !auto && pkColumnType = 'Long'> - /** 防止精度丢失 */ - @JsonSerialize(using= ToStringSerializer.class) - - - private ${column.columnType} ${column.changeColumnName}; + <#if column.remark != ''> + /** ${column.remark} */ + + <#if column.columnKey = 'PRI'> + <#if !auto && pkColumnType = 'Long'> + /** 防止精度丢失 */ + @JsonSerialize(using= ToStringSerializer.class) + + + private ${column.columnType} ${column.changeColumnName}; } diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/Entity.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/Entity.ftl index c164f6f53..bcd8cb208 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/Entity.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/Entity.ftl @@ -1,69 +1,47 @@ -package ${package}.domain; +package ${package}.service.dao; +<#if hasPk> +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; + +import lombok.Builder; import lombok.Data; -import cn.hutool.core.bean.BeanUtil; +import lombok.EqualsAndHashCode; -import cn.hutool.core.bean.copier.CopyOptions; -import javax.persistence.*; -<#if isNotNullColumns??> - import javax.validation.constraints.*; - -<#if hasDateAnnotation> - import javax.persistence.Entity; - import javax.persistence.Table; - import org.hibernate.annotations.*; - <#if hasTimestamp> - import java.sql.Timestamp; +import java.sql.Timestamp; <#if hasBigDecimal> - import java.math.BigDecimal; +import java.math.BigDecimal; import java.io.Serializable; /** -* @description / +* @description 添加'@Builder'注解最好不好添加'@NoArgsConstructor' * @author ${author} * @date ${date} **/ -@Entity @Data -@Table(name="${tableName}") +@Builder +@EqualsAndHashCode(callSuper = false) +@TableName("${tableName}") public class ${className} implements Serializable { + + private static final long serialVersionUID = 1L; + <#if columns??> - <#list columns as column> - - <#if column.columnKey = 'PRI'> - @Id - <#if auto> - @GeneratedValue(strategy = GenerationType.IDENTITY) - - - @Column(name = "${column.columnName}"<#if column.columnKey = 'UNI'>,unique = true<#if column.istNotNull && column.columnKey != 'PRI'>,nullable = false) - <#if column.istNotNull && column.columnKey != 'PRI'> - <#if column.columnType = 'String'> - @NotBlank - <#else> - @NotNull - - - <#if (column.dateAnnotation)?? && column.dateAnnotation != ''> - <#if column.dateAnnotation = 'CreationTimestamp'> - @CreationTimestamp - <#else> - @UpdateTimestamp - - - <#if column.remark != ''> - - <#else> - - - private ${column.columnType} ${column.changeColumnName}; - +<#list columns as column> +<#if column.columnKey = 'PRI'> + @TableId(value = "${column.columnName}", type = <#if auto>IdType.AUTO<#else>IdType.NONE) +<#if column.remark != ''> + /** ${column.remark} */ +<#else> + /** ${column.changeColumnName} */ + + private ${column.columnType} ${column.changeColumnName}; -public void copy(${className} source){ -BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); -} + + } diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/Mapper.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/Mapper.ftl index 2386841ef..0ab095291 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/Mapper.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/Mapper.ftl @@ -1,17 +1,12 @@ -package ${package}.service.mapstruct; +package ${package}.service.dao.mapper; -import BaseMapper; -import ${package}.domain.${className}; -import ${package}.service.dto.${className}Dto; -import org.mapstruct.Mapper; -import org.mapstruct.ReportingPolicy; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import ${package}.service.dao.${className}; /** -* @website https://el-admin.vip * @author ${author} * @date ${date} **/ -@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) -public interface ${className}Mapper extends BaseMapper<${className}Dto, ${className}> { +public interface ${className}Mapper extends BaseMapper<${className}> { } diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/MySQLMapper.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/MySQLMapper.ftl new file mode 100644 index 000000000..e4f04136b --- /dev/null +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/MySQLMapper.ftl @@ -0,0 +1,5 @@ + + + + + diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/QueryCriteria.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/QueryCriteria.ftl index 0ba4c80c3..d991085c7 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/QueryCriteria.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/QueryCriteria.ftl @@ -1,66 +1,12 @@ - package ${package}.service.dto; -import lombok.Data; -<#if queryHasTimestamp> -import java.sql.Timestamp; - -<#if queryHasBigDecimal> -import java.math.BigDecimal; - -<#if betweens??> -import java.util.List; - -<#if queryColumns??> -import Query; - +import org.nl.common.domain.query.BaseQuery; +import ${package}.service.dao.${className}; /** * @author ${author} * @date ${date} **/ -@Data -public class ${className}QueryCriteria{ -<#if queryColumns??> - <#list queryColumns as column> +public class ${className}Query extends BaseQuery<${className}> { -<#if column.queryType = '='> - /** 精确 */ - @Query - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = 'Like'> - /** 模糊 */ - @Query(type = Query.Type.INNER_LIKE) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '!='> - /** 不等于 */ - @Query(type = Query.Type.NOT_EQUAL) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = 'NotNull'> - /** 不为空 */ - @Query(type = Query.Type.NOT_NULL) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '>='> - /** 大于等于 */ - @Query(type = Query.Type.GREATER_THAN) - private ${column.columnType} ${column.changeColumnName}; - -<#if column.queryType = '<='> - /** 小于等于 */ - @Query(type = Query.Type.LESS_THAN) - private ${column.columnType} ${column.changeColumnName}; - - - -<#if betweens??> - <#list betweens as column> - /** BETWEEN */ - @Query(type = Query.Type.BETWEEN) - private List<${column.columnType}> ${column.changeColumnName}; - - } diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/Service.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/Service.ftl index bb49bfd7a..04c592ed4 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/Service.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/Service.ftl @@ -1,64 +1,43 @@ - package ${package}.service; -import org.springframework.data.domain.Pageable; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.nl.common.domain.query.PageQuery; +import com.baomidou.mybatisplus.extension.service.IService; +import ${package}.service.dao.${className}; + import java.util.Map; -import java.util.List; -import java.io.IOException; -import javax.servlet.http.HttpServletResponse; +import java.util.Set; /** * @description 服务接口 * @author ${author} * @date ${date} **/ -public interface ${className}Service { +public interface I${className}Service extends IService<${className}> { -/** -* 查询数据分页 -* @param whereJson 条件 -* @param page 分页参数 -* @return Map -*/ -Map queryAll(Map whereJson, Pageable page); - -/** -* 查询所有数据不分页 -* @param whereJson 条件参数 -* @return List<${className}Dto> + /** + * 查询数据分页 + * @param whereJson 条件 + * @param pageable 分页参数 + * @return IPage<${className}> */ - List<${className}Dto> queryAll(Map whereJson); + IPage<${className}> queryAll(Map whereJson, PageQuery pageable); - /** - * 根据ID查询 - * @param ${pkChangeColName} ID - * @return ${className} - */ - ${className}Dto findById(${pkColumnType} ${pkChangeColName}); + /** + * 创建 + * @param entity / + */ + void create(${className} entity); - /** - * 根据编码查询 - * @param code code - * @return ${className} - */ - ${className}Dto findByCode(String code); + /** + * 编辑 + * @param entity / + */ + void update(${className} entity); - - /** - * 创建 - * @param dto / - */ - void create(${className}Dto dto); - - /** - * 编辑 - * @param dto / - */ - void update(${className}Dto dto); - - /** - * 多选删除 - * @param ids / - */ - void deleteAll(${pkColumnType}[] ids); - } + /** + * 多选删除 + * @param ids / + */ + void deleteAll(Set ids); +} diff --git a/lms/nladmin-system/src/main/resources/template/generator/admin/ServiceImpl.ftl b/lms/nladmin-system/src/main/resources/template/generator/admin/ServiceImpl.ftl index f1c872823..5e504d265 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/admin/ServiceImpl.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/admin/ServiceImpl.ftl @@ -1,128 +1,80 @@ - package ${package}.service.impl; - -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import org.springframework.data.domain.Pageable; -import java.util.List; -import java.util.Map; - import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import org.nl.common.utils.SecurityUtils; -import org.nl.modules.wql.core.bean.ResultBean; -import org.nl.modules.wql.core.bean.WQLObject; -import org.nl.modules.wql.util.WqlUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import cn.hutool.core.util.ObjectUtil; +import org.nl.modules.common.exception.BadRequestException; +import org.nl.common.domain.query.PageQuery; +import org.nl.common.utils.SecurityUtils; +import ${package}.service.I${className}Service; +import ${package}.service.dao.mapper.${className}Mapper; +import ${package}.service.dao.${className}; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Map; +import java.util.Set; /** * @description 服务实现 * @author ${author} * @date ${date} **/ -@Service -@RequiredArgsConstructor @Slf4j -public class ${className}ServiceImpl implements ${className}Service { +@Service +public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}> implements I${className}Service { + + @Autowired + private ${className}Mapper ${changeClassName}Mapper; + + @Override + public IPage<${className}> queryAll(Map whereJson, PageQuery page){ + LambdaQueryWrapper<${className}> lam = new LambdaQueryWrapper<>(); + IPage<${className}> pages = new Page<>(page.getPage() + 1, page.getSize()); + ${changeClassName}Mapper.selectPage(pages, lam); + return pages; + } + + @Override + public void create(${className} entity) { + String currentUserId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + + entity.set${pkChangeColName ? cap_first }(IdUtil.getSnowflake(1, 1).nextIdStr()); + entity.setCreate_id(currentUserId); + entity.setCreate_name(nickName); + entity.setCreate_time(now); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); + ${changeClassName}Mapper.insert(entity); + } + + @Override + public void update(${className} entity) { + ${className} dto = ${changeClassName}Mapper.selectById(entity.get${pkChangeColName ? cap_first }()); + if (dto == null) throw new BadRequestException("被删除或无权限,操作失败!"); + + String currentUserId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + entity.setUpdate_id(currentUserId); + entity.setUpdate_name(nickName); + entity.setUpdate_time(now); + + ${changeClassName}Mapper.updateById(entity); + } + + @Override + public void deleteAll(Set ids) { + // 真删除 + ${changeClassName}Mapper.deleteBatchIds(ids); + } -@Override -public Map queryAll(Map whereJson, Pageable page){ -WQLObject wo = WQLObject.getWQLObject("${tableName}"); -ResultBean rb = wo.pagequery(WqlUtil.getHttpContext(page), "1=1", "update_time desc"); -final JSONObject json = rb.pageResult(); -return json; } - -@Override -public List<${className}Dto> queryAll(Map whereJson){ - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONArray arr = wo.query().getResultJSONArray(0); - if (ObjectUtil.isNotEmpty(arr)) return arr.toJavaList(${className}Dto.class); - return null; - } - - @Override - public ${className}Dto findById(${pkColumnType} ${pkChangeColName}) { - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = wo.query("${pkChangeColName} = '" + ${pkChangeColName} + "'").uniqueResult(0); - if (ObjectUtil.isNotEmpty(json)){ - return json.toJavaObject( ${className}Dto.class); - } - return null; - } - - @Override - public ${className}Dto findByCode(String code) { - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = wo.query("code ='" + code + "'").uniqueResult(0); - if (ObjectUtil.isNotEmpty(json)){ - return json.toJavaObject( ${className}Dto.class); - } - return null; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void create(${className}Dto dto) { - String currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - - dto.set${pkChangeColName ? cap_first }(IdUtil.getSnowflake(1, 1).nextId()); - dto.setCreate_id(currentUserId); - dto.setCreate_name(nickName); - dto.setUpdate_optid(currentUserId); - dto.setUpdate_optname(nickName); - dto.setUpdate_time(now); - dto.setCreate_time(now); - - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = JSONObject.parseObject(JSON.toJSONString(dto)); - wo.insert(json); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void update(${className}Dto dto) { - ${className}Dto entity = this.findById(dto.get${pkChangeColName ? cap_first }()); - if (entity == null) throw new BadRequestException("被删除或无权限,操作失败!"); - - String currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - - String now = DateUtil.now(); - dto.setUpdate_time(now); - dto.setUpdate_optid(currentUserId); - dto.setUpdate_optname(nickName); - - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - JSONObject json = JSONObject.parseObject(JSON.toJSONString(dto)); - wo.update(json); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void deleteAll(${pkColumnType}[] ids) { - String currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - - WQLObject wo = WQLObject.getWQLObject("${tableName}"); - for (${pkColumnType} ${pkChangeColName}: ids) { - JSONObject param = new JSONObject(); - param.put("${pkChangeColName}", String.valueOf(${pkChangeColName})); - param.put("is_delete", "1"); - param.put("update_optid", currentUserId); - param.put("update_optname", nickName); - param.put("update_time", now); - wo.update(param); - } - } - - } diff --git a/lms/nladmin-system/src/main/resources/template/generator/front/index.ftl b/lms/nladmin-system/src/main/resources/template/generator/front/index.ftl index 8fe068dd7..d793e3022 100644 --- a/lms/nladmin-system/src/main/resources/template/generator/front/index.ftl +++ b/lms/nladmin-system/src/main/resources/template/generator/front/index.ftl @@ -113,13 +113,20 @@