集成 Spring Boot Admin 监控服务端及客户端依赖,并新增 AdminServerConfig 配置类启用应用监控。
This commit is contained in:
1 parent
2931153422
commit
63c8cbc873
45 files changed
+257
-140
No files matched your search
@@ -0,0 +1,113 @@
|
||||
package com.youlai.boot.module.codegen.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.core.web.PageResult;
|
||||
import com.youlai.boot.core.web.Result;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.common.enums.LogModuleEnum;
|
||||
import com.youlai.boot.module.codegen.service.CodegenService;
|
||||
import com.youlai.boot.module.codegen.model.form.GenConfigForm;
|
||||
import com.youlai.boot.module.codegen.model.query.TableQuery;
|
||||
import com.youlai.boot.module.codegen.model.vo.CodegenPreviewVO;
|
||||
import com.youlai.boot.module.codegen.model.vo.TablePageVO;
|
||||
import com.youlai.boot.common.annotation.Log;
|
||||
import com.youlai.boot.module.codegen.service.GenTableService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.ServletOutputStream;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 代码生成器控制层
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Tag(name = "11.代码生成")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/codegen")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class CodegenController {
|
||||
|
||||
private final CodegenService codegenService;
|
||||
private final GenTableService genTableService;
|
||||
private final CodegenProperties codegenProperties;
|
||||
|
||||
@Operation(summary = "获取数据表分页列表")
|
||||
@GetMapping("/table")
|
||||
@Log(value = "代码生成分页列表", module = LogModuleEnum.OTHER)
|
||||
public PageResult<TablePageVO> getTablePage(
|
||||
TableQuery queryParams
|
||||
) {
|
||||
Page<TablePageVO> result = codegenService.getTablePage(queryParams);
|
||||
return PageResult.success(result);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取代码生成配置")
|
||||
@GetMapping("/{tableName}/config")
|
||||
public Result<GenConfigForm> getGenTableFormData(
|
||||
@Parameter(description = "表名", example = "sys_user") @PathVariable String tableName
|
||||
) {
|
||||
GenConfigForm formData = genTableService.getGenTableFormData(tableName);
|
||||
return Result.success(formData);
|
||||
}
|
||||
|
||||
@Operation(summary = "保存代码生成配置")
|
||||
@PostMapping("/{tableName}/config")
|
||||
@Log(value = "生成代码", module = LogModuleEnum.OTHER)
|
||||
public Result<?> saveGenConfig(@RequestBody GenConfigForm formData) {
|
||||
genTableService.saveGenConfig(formData);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "删除代码生成配置")
|
||||
@DeleteMapping("/{tableName}/config")
|
||||
public Result<?> deleteGenConfig(
|
||||
@Parameter(description = "表名", example = "sys_user") @PathVariable String tableName
|
||||
) {
|
||||
genTableService.deleteGenConfig(tableName);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "获取预览生成代码")
|
||||
@GetMapping("/{tableName}/preview")
|
||||
@Log(value = "预览生成代码", module = LogModuleEnum.OTHER)
|
||||
public Result<List<CodegenPreviewVO>> getTablePreviewData(@PathVariable String tableName,
|
||||
@RequestParam(value = "pageType", required = false, defaultValue = "classic") String pageType,
|
||||
@RequestParam(value = "type", required = false, defaultValue = "ts") String type) {
|
||||
List<CodegenPreviewVO> list = codegenService.getCodegenPreviewData(tableName, pageType, type);
|
||||
return Result.success(list);
|
||||
}
|
||||
|
||||
@Operation(summary = "下载代码")
|
||||
@GetMapping("/{tableName}/download")
|
||||
@Log(value = "下载代码", module = LogModuleEnum.OTHER)
|
||||
public void downloadZip(HttpServletResponse response, @PathVariable String tableName,
|
||||
@RequestParam(value = "pageType", required = false, defaultValue = "classic") String pageType,
|
||||
@RequestParam(value = "type", required = false, defaultValue = "ts") String type) {
|
||||
String[] tableNames = tableName.split(",");
|
||||
byte[] data = codegenService.downloadCode(tableNames, pageType, type);
|
||||
|
||||
response.reset();
|
||||
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(codegenProperties.getDownloadFileName(), StandardCharsets.UTF_8));
|
||||
response.setContentType("application/octet-stream; charset=UTF-8");
|
||||
|
||||
try (ServletOutputStream outputStream = response.getOutputStream()) {
|
||||
outputStream.write(data);
|
||||
outputStream.flush();
|
||||
} catch (IOException e) {
|
||||
log.error("Error while writing the zip file1 to response", e);
|
||||
throw new RuntimeException("Failed to write the zip file1 to response", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.youlai.boot.module.codegen.converter;
|
||||
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import com.youlai.boot.module.codegen.model.form.GenConfigForm;
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 代码生成配置转换器
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface CodegenConverter {
|
||||
|
||||
@Mapping(source = "genTable.tableName", target = "tableName")
|
||||
@Mapping(source = "genTable.businessName", target = "businessName")
|
||||
@Mapping(source = "genTable.moduleName", target = "moduleName")
|
||||
@Mapping(source = "genTable.packageName", target = "packageName")
|
||||
@Mapping(source = "genTable.entityName", target = "entityName")
|
||||
@Mapping(source = "genTable.author", target = "author")
|
||||
@Mapping(source = "genTable.pageType", target = "pageType")
|
||||
@Mapping(source = "genTable.removeTablePrefix", target = "removeTablePrefix")
|
||||
@Mapping(source = "fieldConfigs", target = "fieldConfigs")
|
||||
GenConfigForm toGenConfigForm(GenTable genTable, List<GenTableColumn> fieldConfigs);
|
||||
|
||||
List<GenConfigForm.FieldConfig> toGenTableColumnForm(List<GenTableColumn> fieldConfigs);
|
||||
|
||||
GenConfigForm.FieldConfig toGenTableColumnForm(GenTableColumn genTableColumn);
|
||||
|
||||
GenTable toGenTable(GenConfigForm formData);
|
||||
|
||||
List<GenTableColumn> toGenTableColumn(List<GenConfigForm.FieldConfig> fieldConfigs);
|
||||
|
||||
GenTableColumn toGenTableColumn(GenConfigForm.FieldConfig fieldConfig);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.youlai.boot.module.codegen.enums;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.EnumValue;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import com.youlai.boot.common.base.IBaseEnum;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
/**
|
||||
* 表单类型枚举
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum FormTypeEnum implements IBaseEnum<Integer> {
|
||||
|
||||
/**
|
||||
* 输入框
|
||||
*/
|
||||
INPUT(1, "输入框"),
|
||||
|
||||
/**
|
||||
* 下拉框
|
||||
*/
|
||||
SELECT(2, "下拉框"),
|
||||
|
||||
/**
|
||||
* 单选框
|
||||
*/
|
||||
RADIO(3, "单选框"),
|
||||
|
||||
/**
|
||||
* 复选框
|
||||
*/
|
||||
CHECK_BOX(4, "复选框"),
|
||||
|
||||
/**
|
||||
* 数字输入框
|
||||
*/
|
||||
INPUT_NUMBER(5, "数字输入框"),
|
||||
|
||||
/**
|
||||
* 开关
|
||||
*/
|
||||
SWITCH(6, "开关"),
|
||||
|
||||
/**
|
||||
* 文本域
|
||||
*/
|
||||
TEXT_AREA(7, "文本域"),
|
||||
|
||||
/**
|
||||
* 日期时间框
|
||||
*/
|
||||
DATE(8, "日期框"),
|
||||
|
||||
/**
|
||||
* 日期框
|
||||
*/
|
||||
DATE_TIME(9, "日期时间框"),
|
||||
|
||||
/**
|
||||
* 隐藏域
|
||||
*/
|
||||
HIDDEN(10, "隐藏域");
|
||||
|
||||
|
||||
// Mybatis-Plus 提供注解表示插入数据库时插入该值
|
||||
@EnumValue
|
||||
@JsonValue
|
||||
private final Integer value;
|
||||
|
||||
// @JsonValue // 表示对枚举序列化时返回此字段
|
||||
private final String label;
|
||||
|
||||
|
||||
@JsonCreator
|
||||
public static FormTypeEnum fromValue(Integer value) {
|
||||
for (FormTypeEnum type : FormTypeEnum.values()) {
|
||||
if (type.getValue().equals(value)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No enum constant with value " + value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.youlai.boot.module.codegen.enums;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 表单类型枚举
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Getter
|
||||
public enum JavaTypeEnum {
|
||||
|
||||
VARCHAR("varchar", "String", "string"),
|
||||
CHAR("char", "String", "string"),
|
||||
BLOB("blob", "byte[]", "Uint8Array"),
|
||||
TEXT("text", "String", "string"),
|
||||
JSON("json", "String", "any"),
|
||||
INTEGER("int", "Integer", "number"),
|
||||
TINYINT("tinyint", "Integer", "number"),
|
||||
SMALLINT("smallint", "Integer", "number"),
|
||||
MEDIUMINT("mediumint", "Integer", "number"),
|
||||
BIGINT("bigint", "Long", "number"),
|
||||
FLOAT("float", "Float", "number"),
|
||||
DOUBLE("double", "Double", "number"),
|
||||
DECIMAL("decimal", "BigDecimal", "number"),
|
||||
DATE("date", "LocalDate", "string"),
|
||||
DATETIME("datetime", "LocalDateTime", "string"),
|
||||
TIMESTAMP("timestamp", "LocalDateTime", "string"),
|
||||
BOOLEAN("boolean", "Boolean", "boolean"),
|
||||
BIT("bit", "Boolean", "boolean");
|
||||
|
||||
// 数据库类型
|
||||
private final String dbType;
|
||||
// Java类型
|
||||
private final String javaType;
|
||||
// TypeScript类型
|
||||
private final String tsType;
|
||||
|
||||
// 数据库类型和Java类型的映射
|
||||
private static final Map<String, JavaTypeEnum> typeMap = new HashMap<>();
|
||||
|
||||
// 初始化映射关系
|
||||
static {
|
||||
for (JavaTypeEnum javaTypeEnum : JavaTypeEnum.values()) {
|
||||
typeMap.put(javaTypeEnum.getDbType(), javaTypeEnum);
|
||||
}
|
||||
}
|
||||
|
||||
JavaTypeEnum(String dbType, String javaType, String tsType) {
|
||||
this.dbType = dbType;
|
||||
this.javaType = javaType;
|
||||
this.tsType = tsType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据数据库类型获取对应的Java类型
|
||||
*
|
||||
* @param columnType 列类型
|
||||
* @return 对应的Java类型
|
||||
*/
|
||||
public static String getJavaTypeByColumnType(String columnType) {
|
||||
String normalized = normalizeColumnType(columnType);
|
||||
JavaTypeEnum javaTypeEnum = typeMap.get(normalized);
|
||||
if (javaTypeEnum != null) {
|
||||
return javaTypeEnum.getJavaType();
|
||||
}
|
||||
return "String";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Java类型获取对应的TypeScript类型
|
||||
*
|
||||
* @param javaType Java类型
|
||||
* @return 对应的TypeScript类型
|
||||
*/
|
||||
public static String getTsTypeByJavaType(String javaType) {
|
||||
if (javaType == null) {
|
||||
return "any";
|
||||
}
|
||||
for (JavaTypeEnum javaTypeEnum : JavaTypeEnum.values()) {
|
||||
if (javaTypeEnum.getJavaType().equals(javaType)) {
|
||||
return javaTypeEnum.getTsType();
|
||||
}
|
||||
}
|
||||
return "any";
|
||||
}
|
||||
|
||||
private static String normalizeColumnType(String columnType) {
|
||||
if (columnType == null) {
|
||||
return "";
|
||||
}
|
||||
// Handle values like: varchar(255), bigint unsigned, INT
|
||||
String normalized = columnType.trim().toLowerCase();
|
||||
int parenIndex = normalized.indexOf('(');
|
||||
if (parenIndex > -1) {
|
||||
normalized = normalized.substring(0, parenIndex);
|
||||
}
|
||||
// Remove modifiers
|
||||
normalized = normalized.replace("unsigned", "").replace("zerofill", "").trim();
|
||||
// Collapse repeated spaces
|
||||
normalized = normalized.replaceAll("\\s+", " ");
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.youlai.boot.module.codegen.enums;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.EnumValue;
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
import com.youlai.boot.common.base.IBaseEnum;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
/**
|
||||
* 查询类型枚举
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Getter
|
||||
@RequiredArgsConstructor
|
||||
public enum QueryTypeEnum implements IBaseEnum<Integer> {
|
||||
|
||||
/** 等于 */
|
||||
EQ(1, "="),
|
||||
|
||||
/** 模糊匹配 */
|
||||
LIKE(2, "LIKE '%s%'"),
|
||||
|
||||
/** 包含 */
|
||||
IN(3, "IN"),
|
||||
|
||||
/** 范围 */
|
||||
BETWEEN(4, "BETWEEN"),
|
||||
|
||||
/** 大于 */
|
||||
GT(5, ">"),
|
||||
|
||||
/** 大于等于 */
|
||||
GE(6, ">="),
|
||||
|
||||
/** 小于 */
|
||||
LT(7, "<"),
|
||||
|
||||
/** 小于等于 */
|
||||
LE(8, "<="),
|
||||
|
||||
/** 不等于 */
|
||||
NE(9, "!="),
|
||||
|
||||
/** 左模糊匹配 */
|
||||
LIKE_LEFT(10, "LIKE '%s'"),
|
||||
|
||||
/** 右模糊匹配 */
|
||||
LIKE_RIGHT(11, "LIKE 's%'");
|
||||
|
||||
|
||||
// 存储在数据库中的枚举属性值
|
||||
@EnumValue
|
||||
@JsonValue
|
||||
private final Integer value;
|
||||
|
||||
// 序列化成 JSON 时的属性值
|
||||
private final String label;
|
||||
|
||||
|
||||
@JsonCreator
|
||||
public static QueryTypeEnum fromValue(Integer value) {
|
||||
for (QueryTypeEnum type : QueryTypeEnum.values()) {
|
||||
if (type.getValue().equals(value)) {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("No enum constant with value " + value);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.youlai.boot.module.codegen.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.module.codegen.model.bo.ColumnMetaData;
|
||||
import com.youlai.boot.module.codegen.model.bo.TableMetaData;
|
||||
import com.youlai.boot.module.codegen.model.query.TableQuery;
|
||||
import com.youlai.boot.module.codegen.model.vo.TablePageVO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* 数据库映射层
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.9.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface DatabaseMapper extends BaseMapper {
|
||||
|
||||
/**
|
||||
* 获取表分页列表
|
||||
*
|
||||
* @param page
|
||||
* @param queryParams
|
||||
* @return
|
||||
*/
|
||||
Page<TablePageVO> getTablePage(Page<TablePageVO> page, TableQuery queryParams);
|
||||
|
||||
/**
|
||||
* 获取表字段列表
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
List<ColumnMetaData> getTableColumns(String tableName);
|
||||
|
||||
/**
|
||||
* 获取表元数据
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
TableMetaData getTableMetadata(String tableName);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.youlai.boot.module.codegen.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 代码生成表字段配置访问层
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface GenTableColumnMapper extends BaseMapper<GenTableColumn> {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.youlai.boot.module.codegen.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
/**
|
||||
* 代码生成表配置访问层
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Mapper
|
||||
public interface GenTableMapper extends BaseMapper<GenTable> {
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.youlai.boot.module.codegen.model.bo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "数据表字段Vo")
|
||||
@Data
|
||||
public class ColumnMetaData {
|
||||
|
||||
/**
|
||||
* 字段名称
|
||||
*/
|
||||
private String columnName;
|
||||
|
||||
/**
|
||||
* 字段类型
|
||||
*/
|
||||
private String dataType;
|
||||
|
||||
/**
|
||||
* 字段描述
|
||||
*/
|
||||
private String columnComment;
|
||||
|
||||
/**
|
||||
* 字段长度
|
||||
*/
|
||||
private Long characterMaximumLength;
|
||||
|
||||
/**
|
||||
* 是否主键(1-是 0-否)
|
||||
*/
|
||||
private Integer isPrimaryKey;
|
||||
|
||||
/**
|
||||
* 是否可为空(1-是 0-否)
|
||||
*/
|
||||
private String isNullable;
|
||||
|
||||
/**
|
||||
* 字符集
|
||||
*/
|
||||
private String characterSetName;
|
||||
|
||||
/**
|
||||
* 排序规则
|
||||
*/
|
||||
private String collationName;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.youlai.boot.module.codegen.model.bo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
/**
|
||||
* 数据表元数据
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Data
|
||||
public class TableMetaData {
|
||||
|
||||
/**
|
||||
* 表名称
|
||||
*/
|
||||
private String tableName;
|
||||
|
||||
/**
|
||||
* 表描述
|
||||
*/
|
||||
private String tableComment;
|
||||
|
||||
/**
|
||||
* 排序规则
|
||||
*/
|
||||
private String tableCollation;
|
||||
|
||||
/**
|
||||
* 存储引擎
|
||||
*/
|
||||
private String engine;
|
||||
|
||||
/**
|
||||
* 字符集
|
||||
*/
|
||||
private String charset;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private String createTime;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.youlai.boot.module.codegen.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 代码生成表配置
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@TableName(value = "gen_table")
|
||||
@Getter
|
||||
@Setter
|
||||
public class GenTable extends BaseEntity {
|
||||
|
||||
/**
|
||||
* 表名
|
||||
*/
|
||||
private String tableName;
|
||||
|
||||
/**
|
||||
* 包名
|
||||
*/
|
||||
private String packageName;
|
||||
|
||||
/**
|
||||
* 模块名
|
||||
*/
|
||||
private String moduleName;
|
||||
|
||||
/**
|
||||
* 实体类名
|
||||
*/
|
||||
private String entityName;
|
||||
|
||||
/**
|
||||
* 业务名
|
||||
*/
|
||||
private String businessName;
|
||||
|
||||
/**
|
||||
* 父菜单ID
|
||||
*/
|
||||
private Long parentMenuId;
|
||||
|
||||
/**
|
||||
* 作者
|
||||
*/
|
||||
private String author;
|
||||
|
||||
/**
|
||||
* 页面类型 classic|curd
|
||||
*/
|
||||
private String pageType;
|
||||
|
||||
/**
|
||||
* 要移除的表前缀,如: sys_
|
||||
*/
|
||||
private String removeTablePrefix;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.youlai.boot.module.codegen.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import com.youlai.boot.module.codegen.enums.FormTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.QueryTypeEnum;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 代码生成表字段配置实体
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@TableName(value = "gen_table_column")
|
||||
@Getter
|
||||
@Setter
|
||||
public class GenTableColumn extends BaseEntity {
|
||||
|
||||
|
||||
/**
|
||||
* 关联的表配置ID
|
||||
*/
|
||||
private Long tableId;
|
||||
|
||||
/**
|
||||
* 列名
|
||||
*/
|
||||
private String columnName;
|
||||
|
||||
/**
|
||||
* 列类型
|
||||
*/
|
||||
private String columnType;
|
||||
|
||||
/**
|
||||
* 字段长度
|
||||
*/
|
||||
private Long maxLength;
|
||||
|
||||
/**
|
||||
* 字段名称
|
||||
*/
|
||||
private String fieldName;
|
||||
|
||||
/**
|
||||
* 字段排序
|
||||
*/
|
||||
private Integer fieldSort;
|
||||
|
||||
/**
|
||||
* 字段类型
|
||||
*/
|
||||
private String fieldType;
|
||||
|
||||
/**
|
||||
* 字段描述
|
||||
*/
|
||||
private String fieldComment;
|
||||
|
||||
/**
|
||||
* 表单类型
|
||||
*/
|
||||
private FormTypeEnum formType;
|
||||
|
||||
/**
|
||||
* 查询方式
|
||||
*/
|
||||
private QueryTypeEnum queryType;
|
||||
|
||||
/**
|
||||
* 是否在列表显示
|
||||
*/
|
||||
private Integer isShowInList;
|
||||
|
||||
/**
|
||||
* 是否在表单显示
|
||||
*/
|
||||
private Integer isShowInForm;
|
||||
|
||||
/**
|
||||
* 是否在查询条件显示
|
||||
*/
|
||||
private Integer isShowInQuery;
|
||||
|
||||
/**
|
||||
* 是否必填
|
||||
*/
|
||||
private Integer isRequired;
|
||||
|
||||
/**
|
||||
* TypeScript类型
|
||||
*/
|
||||
@TableField(exist = false)
|
||||
@JsonIgnore
|
||||
private String tsType;
|
||||
|
||||
/**
|
||||
* 字典类型
|
||||
*/
|
||||
private String dictType;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.youlai.boot.module.codegen.model.form;
|
||||
|
||||
import com.youlai.boot.module.codegen.enums.FormTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.QueryTypeEnum;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 代码生成配置表单
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Schema(description = "代码生成配置表单")
|
||||
@Data
|
||||
public class GenConfigForm {
|
||||
|
||||
@Schema(description = "主键",example = "1")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "表名",example = "sys_user")
|
||||
private String tableName;
|
||||
|
||||
@Schema(description = "业务名",example = "用户")
|
||||
private String businessName;
|
||||
|
||||
@Schema(description = "模块名",example = "system")
|
||||
private String moduleName;
|
||||
|
||||
@Schema(description = "包名",example = "com.youlai")
|
||||
private String packageName;
|
||||
|
||||
@Schema(description = "实体名",example = "User")
|
||||
private String entityName;
|
||||
|
||||
@Schema(description = "作者",example = "youlaitech")
|
||||
private String author;
|
||||
|
||||
@Schema(description = "上级菜单ID",example = "1")
|
||||
private Long parentMenuId;
|
||||
|
||||
@Schema(description = "字段配置列表")
|
||||
private List<FieldConfig> fieldConfigs;
|
||||
|
||||
@Schema(description = "后端应用名")
|
||||
private String backendAppName;
|
||||
|
||||
@Schema(description = "前端应用名")
|
||||
private String frontendAppName;
|
||||
|
||||
@Schema(description = "页面类型 classic|curd", example = "classic")
|
||||
private String pageType;
|
||||
|
||||
@Schema(description = "要移除的表前缀,如: sys_", example = "sys_")
|
||||
private String removeTablePrefix;
|
||||
|
||||
@Schema(description = "字段配置")
|
||||
@Data
|
||||
public static class FieldConfig {
|
||||
|
||||
@Schema(description = "主键")
|
||||
private Long id;
|
||||
|
||||
@Schema(description = "列名")
|
||||
private String columnName;
|
||||
|
||||
@Schema(description = "列类型")
|
||||
private String columnType;
|
||||
|
||||
@Schema(description = "字段名")
|
||||
private String fieldName;
|
||||
|
||||
@Schema(description = "字段排序")
|
||||
private Integer fieldSort;
|
||||
|
||||
@Schema(description = "字段类型")
|
||||
private String fieldType;
|
||||
|
||||
@Schema(description = "字段描述")
|
||||
private String fieldComment;
|
||||
|
||||
@Schema(description = "是否在列表显示")
|
||||
private Integer isShowInList;
|
||||
|
||||
@Schema(description = "是否在表单显示")
|
||||
private Integer isShowInForm;
|
||||
|
||||
@Schema(description = "是否在查询条件显示")
|
||||
private Integer isShowInQuery;
|
||||
|
||||
@Schema(description = "是否必填")
|
||||
private Integer isRequired;
|
||||
|
||||
@Schema(description = "最大长度")
|
||||
private Integer maxLength;
|
||||
|
||||
@Schema(description = "表单类型")
|
||||
private FormTypeEnum formType;
|
||||
|
||||
@Schema(description = "查询类型")
|
||||
private QueryTypeEnum queryType;
|
||||
|
||||
@Schema(description = "字典类型")
|
||||
private String dictType;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.youlai.boot.module.codegen.model.query;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.youlai.boot.common.base.BaseQuery;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 数据表分页查询对象
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Schema(description = "数据表分页查询对象")
|
||||
@Getter
|
||||
@Setter
|
||||
public class TablePageQuery extends BaseQuery {
|
||||
|
||||
@Schema(description="关键字(表名)")
|
||||
private String keywords;
|
||||
|
||||
/**
|
||||
* 排除的表名
|
||||
*/
|
||||
@JsonIgnore
|
||||
private List<String> excludeTables;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.youlai.boot.module.codegen.model.query;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.youlai.boot.common.base.BaseQuery;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 数据表查询对象
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Schema(description = "数据表查询对象")
|
||||
@Getter
|
||||
@Setter
|
||||
public class TableQuery extends BaseQuery {
|
||||
|
||||
@Schema(description="关键字(表名)")
|
||||
private String keywords;
|
||||
|
||||
/**
|
||||
* 排除的表名
|
||||
*/
|
||||
@JsonIgnore
|
||||
private List<String> excludeTables;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.youlai.boot.module.codegen.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "代码生成代码预览Vo")
|
||||
@Data
|
||||
public class CodegenPreviewVO {
|
||||
|
||||
@Schema(description = "生成文件路径")
|
||||
private String path;
|
||||
|
||||
@Schema(description = "生成文件名称",example = "SysUser.java" )
|
||||
private String fileName;
|
||||
|
||||
@Schema(description = "生成文件内容")
|
||||
private String content;
|
||||
|
||||
@Schema(description = "文件范围(frontend/backend)")
|
||||
private String scope;
|
||||
|
||||
@Schema(description = "文件语言(扩展名)")
|
||||
private String language;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.youlai.boot.module.codegen.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
@Schema(description = "表视图对象")
|
||||
@Data
|
||||
public class TablePageVO {
|
||||
|
||||
@Schema(description = "表名称", example = "sys_user")
|
||||
private String tableName;
|
||||
|
||||
@Schema(description = "表描述",example = "用户表")
|
||||
private String tableComment;
|
||||
|
||||
@Schema(description = "表排序规则",example = "utf8mb4_general_ci")
|
||||
private String tableCollation;
|
||||
|
||||
@Schema(description = "存储引擎",example = "InnoDB")
|
||||
private String engine;
|
||||
|
||||
@Schema(description = "字符集",example = "utf8mb4")
|
||||
private String charset;
|
||||
|
||||
@Schema(description = "创建时间",example = "2023-08-08 08:08:08")
|
||||
private String createTime;
|
||||
|
||||
@Schema(description="是否已配置")
|
||||
private Integer isConfigured;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.youlai.boot.module.codegen.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.module.codegen.model.query.TableQuery;
|
||||
import com.youlai.boot.module.codegen.model.vo.CodegenPreviewVO;
|
||||
import com.youlai.boot.module.codegen.model.vo.TablePageVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 代码生成配置接口
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
public interface CodegenService {
|
||||
|
||||
/**
|
||||
* 获取数据表分页列表
|
||||
*
|
||||
* @param queryParams 查询参数
|
||||
* @return
|
||||
*/
|
||||
Page<TablePageVO> getTablePage(TableQuery queryParams);
|
||||
|
||||
/**
|
||||
* 获取预览生成代码
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return
|
||||
*/
|
||||
List<CodegenPreviewVO> getCodegenPreviewData(String tableName, String pageType, String type);
|
||||
|
||||
/**
|
||||
* 下载代码
|
||||
* @param tableNames 表名
|
||||
* @return
|
||||
*/
|
||||
byte[] downloadCode(String[] tableNames, String pageType, String type);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.youlai.boot.module.codegen.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
|
||||
/**
|
||||
* 代码生成配置接口
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
public interface GenTableColumnService extends IService<GenTableColumn> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.youlai.boot.module.codegen.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.module.codegen.model.form.GenConfigForm;
|
||||
|
||||
/**
|
||||
* 代码生成配置接口
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
public interface GenTableService extends IService<GenTable> {
|
||||
|
||||
/**
|
||||
* 获取代码生成配置
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return
|
||||
*/
|
||||
GenConfigForm getGenTableFormData(String tableName);
|
||||
|
||||
/**
|
||||
* 保存代码生成配置
|
||||
*
|
||||
* @param formData 表单数据
|
||||
* @return
|
||||
*/
|
||||
void saveGenConfig(GenConfigForm formData);
|
||||
|
||||
/**
|
||||
* 删除代码生成配置
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return
|
||||
*/
|
||||
void deleteGenConfig(String tableName);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package com.youlai.boot.module.codegen.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.file.FileNameUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.template.Template;
|
||||
import cn.hutool.extra.template.TemplateConfig;
|
||||
import cn.hutool.extra.template.TemplateEngine;
|
||||
import cn.hutool.extra.template.TemplateUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.module.codegen.enums.JavaTypeEnum;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.service.GenTableService;
|
||||
import com.youlai.boot.module.codegen.service.GenTableColumnService;
|
||||
import com.youlai.boot.module.codegen.service.CodegenService;
|
||||
import com.youlai.boot.core.exception.BusinessException;
|
||||
import com.youlai.boot.module.codegen.mapper.DatabaseMapper;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import com.youlai.boot.module.codegen.model.query.TableQuery;
|
||||
import com.youlai.boot.module.codegen.model.vo.CodegenPreviewVO;
|
||||
import com.youlai.boot.module.codegen.model.vo.TablePageVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* 代码生成服务实现类。
|
||||
*
|
||||
* <p>
|
||||
* 根据代码生成配置({@link CodegenProperties})与表/字段元数据,渲染模板并提供预览与下载能力。
|
||||
* </p>
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class CodegenServiceImpl implements CodegenService {
|
||||
|
||||
private final DatabaseMapper databaseMapper;
|
||||
private final CodegenProperties codegenProperties;
|
||||
private final GenTableService genTableService;
|
||||
private final GenTableColumnService genTableColumnService;
|
||||
|
||||
/**
|
||||
* 数据表分页列表
|
||||
*
|
||||
* @param queryParams 查询参数
|
||||
* @return 分页结果
|
||||
*/
|
||||
public Page<TablePageVO> getTablePage(TableQuery queryParams) {
|
||||
Page<TablePageVO> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
|
||||
// 设置排除的表
|
||||
List<String> excludeTables = codegenProperties.getExcludeTables();
|
||||
queryParams.setExcludeTables(excludeTables);
|
||||
|
||||
return databaseMapper.getTablePage(page, queryParams);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析前端模板路径
|
||||
*
|
||||
* @param templateName 模板标识
|
||||
* @param templateConfig 模板配置
|
||||
* @param frontendType 前端类型
|
||||
* @return 模板路径
|
||||
*/
|
||||
private String resolveFrontendTemplatePath(String templateName,
|
||||
CodegenProperties.TemplateConfig templateConfig,
|
||||
String frontendType) {
|
||||
if (!"js".equals(frontendType)) {
|
||||
return templateConfig.getTemplatePath();
|
||||
}
|
||||
if ("API".equals(templateName)) {
|
||||
return "codegen/frontend/js/api.js.vm";
|
||||
}
|
||||
if ("VIEW".equals(templateName)) {
|
||||
return "codegen/frontend/js/index.js.vue.vm";
|
||||
}
|
||||
return templateConfig.getTemplatePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析前端文件后缀
|
||||
*
|
||||
* @param templateName 模板标识
|
||||
* @param templateConfig 模板配置
|
||||
* @param frontendType 前端类型
|
||||
* @return 文件后缀
|
||||
*/
|
||||
private String resolveFrontendExtension(String templateName,
|
||||
CodegenProperties.TemplateConfig templateConfig,
|
||||
String frontendType) {
|
||||
if (!"js".equals(frontendType)) {
|
||||
return templateConfig.getExtension();
|
||||
}
|
||||
if ("API".equals(templateName) || "API_TYPES".equals(templateName)) {
|
||||
return ".js";
|
||||
}
|
||||
return templateConfig.getExtension();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取预览生成代码
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @return 预览数据
|
||||
*/
|
||||
@Override
|
||||
public List<CodegenPreviewVO> getCodegenPreviewData(String tableName, String pageType, String type) {
|
||||
|
||||
List<CodegenPreviewVO> list = new ArrayList<>();
|
||||
|
||||
GenTable genTable = genTableService.getOne(new LambdaQueryWrapper<GenTable>()
|
||||
.eq(GenTable::getTableName, tableName)
|
||||
);
|
||||
if (genTable == null) {
|
||||
throw new BusinessException("未找到表生成配置");
|
||||
}
|
||||
|
||||
List<GenTableColumn> fieldConfigs = genTableColumnService.list(new LambdaQueryWrapper<GenTableColumn>()
|
||||
.eq(GenTableColumn::getTableId, genTable.getId())
|
||||
.orderByAsc(GenTableColumn::getFieldSort)
|
||||
|
||||
);
|
||||
if (CollectionUtil.isEmpty(fieldConfigs)) {
|
||||
throw new BusinessException("未找到字段生成配置");
|
||||
}
|
||||
|
||||
// 遍历模板配置
|
||||
Map<String, CodegenProperties.TemplateConfig> templateConfigs = codegenProperties.getTemplateConfigs();
|
||||
String frontendType = StrUtil.blankToDefault(type, "ts").toLowerCase();
|
||||
for (Map.Entry<String, CodegenProperties.TemplateConfig> templateConfigEntry : templateConfigs.entrySet()) {
|
||||
CodegenPreviewVO previewVo = new CodegenPreviewVO();
|
||||
|
||||
CodegenProperties.TemplateConfig templateConfig = templateConfigEntry.getValue();
|
||||
|
||||
String templateName = templateConfigEntry.getKey();
|
||||
if ("js".equals(frontendType) && "API_TYPES".equals(templateName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String effectiveTemplatePath = resolveFrontendTemplatePath(templateName, templateConfig, frontendType);
|
||||
String extension = resolveFrontendExtension(templateName, templateConfig, frontendType);
|
||||
|
||||
/* 1. 生成文件名 UserController */
|
||||
// User Role Menu Dept
|
||||
String entityName = genTable.getEntityName();
|
||||
// Controller Service Mapper Entity
|
||||
// .java .ts .vue
|
||||
|
||||
// 文件名 UserController.java
|
||||
String fileName = getFileName(entityName, templateName, extension);
|
||||
previewVo.setFileName(fileName);
|
||||
previewVo.setScope(resolveScope(templateName));
|
||||
previewVo.setLanguage(resolveLanguage(fileName));
|
||||
|
||||
/* 2. 生成文件路径 */
|
||||
// 包名:com.youlai.boot
|
||||
String packageName = genTable.getPackageName();
|
||||
// 模块名:system
|
||||
String moduleName = genTable.getModuleName();
|
||||
// 子包名:controller
|
||||
String subpackageName = templateConfig.getSubpackageName();
|
||||
// 组合成文件路径:src/main/java/com/youlai/boot/system/controller
|
||||
String filePath = getFilePath(templateName, moduleName, packageName, subpackageName, entityName);
|
||||
previewVo.setPath(filePath);
|
||||
|
||||
/* 3. 生成文件内容 */
|
||||
// 将模板文件中的变量替换为具体的值 生成代码内容
|
||||
// 优先使用保存的 ui,没有则使用请求参数
|
||||
String finalType = StrUtil.blankToDefault(genTable.getPageType(), pageType);
|
||||
String content = getCodeContent(
|
||||
effectiveTemplatePath,
|
||||
templateConfig.getSubpackageName(),
|
||||
genTable,
|
||||
fieldConfigs,
|
||||
finalType
|
||||
);
|
||||
previewVo.setContent(content);
|
||||
|
||||
list.add(previewVo);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private String resolveScope(String templateName) {
|
||||
return switch (templateName) {
|
||||
case "API", "API_TYPES", "VIEW" -> "frontend";
|
||||
default -> "backend";
|
||||
};
|
||||
}
|
||||
|
||||
private String resolveLanguage(String fileName) {
|
||||
return FileNameUtil.extName(fileName).toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成文件名。
|
||||
*
|
||||
* <p>部分模板需要使用约定的命名规则(例如前端 API 文件)。</p>
|
||||
*
|
||||
* @param entityName 实体名(例如 User)
|
||||
* @param templateName 模板名(例如 Entity、Controller、API)
|
||||
* @param extension 文件后缀(例如 .java、.ts)
|
||||
* @return 文件名
|
||||
*/
|
||||
private String getFileName(String entityName, String templateName, String extension) {
|
||||
if ("Entity".equals(templateName)) {
|
||||
return entityName + extension;
|
||||
} else if ("MapperXml".equals(templateName)) {
|
||||
return entityName + "Mapper" + extension;
|
||||
} else if ("API".equals(templateName)) {
|
||||
// 生成 user.ts 命名
|
||||
return StrUtil.toSymbolCase(entityName, '-') + extension;
|
||||
} else if ("API_TYPES".equals(templateName)) {
|
||||
// 生成 types/api/user.ts
|
||||
return StrUtil.toSymbolCase(entityName, '-') + extension;
|
||||
} else if ("VIEW".equals(templateName)) {
|
||||
return "index.vue";
|
||||
}
|
||||
return entityName + templateName + extension;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成文件路径。
|
||||
*
|
||||
* @param templateName 模板名
|
||||
* @param moduleName 模块名(例如 system)
|
||||
* @param packageName 包名(例如 com.youlai.boot)
|
||||
* @param subPackageName 子包名(例如 controller、service.impl、api、views)
|
||||
* @param entityName 实体名(例如 User)
|
||||
* @return 生成文件路径
|
||||
*/
|
||||
private String getFilePath(String templateName, String moduleName, String packageName, String subPackageName, String entityName) {
|
||||
String path;
|
||||
if ("MapperXml".equals(templateName)) {
|
||||
path = (codegenProperties.getBackendAppName()
|
||||
+ File.separator
|
||||
+ "src" + File.separator + "main" + File.separator + "resources"
|
||||
+ File.separator + subPackageName
|
||||
+ File.separator + moduleName
|
||||
);
|
||||
} else if ("API".equals(templateName)) {
|
||||
// path = "src/api/system";
|
||||
path = (codegenProperties.getFrontendAppName()
|
||||
+ File.separator + "src"
|
||||
+ File.separator + subPackageName
|
||||
+ File.separator + moduleName
|
||||
);
|
||||
} else if ("API_TYPES".equals(templateName)) {
|
||||
// path = "src/types/api";
|
||||
path = (codegenProperties.getFrontendAppName()
|
||||
+ File.separator + "src"
|
||||
+ File.separator + "types"
|
||||
+ File.separator + "api"
|
||||
);
|
||||
} else if ("VIEW".equals(templateName)) {
|
||||
// path = "src/views/system/user";
|
||||
path = (codegenProperties.getFrontendAppName()
|
||||
+ File.separator + "src"
|
||||
+ File.separator + subPackageName
|
||||
+ File.separator + moduleName
|
||||
+ File.separator + StrUtil.toSymbolCase(entityName, '-')
|
||||
);
|
||||
} else {
|
||||
path = (codegenProperties.getBackendAppName()
|
||||
+ File.separator
|
||||
+ "src" + File.separator + "main" + File.separator + "java"
|
||||
+ File.separator + packageName
|
||||
+ File.separator + moduleName
|
||||
+ File.separator + subPackageName
|
||||
);
|
||||
}
|
||||
|
||||
// subPackageName = model.entity => model/entity
|
||||
path = path.replace(".", File.separator);
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染模板,生成代码内容。
|
||||
*
|
||||
* @param templateConfig 模板配置
|
||||
* @param genTable 表生成配置
|
||||
* @param fieldConfigs 字段配置
|
||||
* @param pageType 前端页面类型
|
||||
* @return 渲染后的代码内容
|
||||
*/
|
||||
private String getCodeContent(String templatePath,
|
||||
String subpackageName,
|
||||
GenTable genTable,
|
||||
List<GenTableColumn> fieldConfigs,
|
||||
String pageType) {
|
||||
|
||||
Map<String, Object> bindMap = new HashMap<>();
|
||||
|
||||
String entityName = genTable.getEntityName();
|
||||
|
||||
bindMap.put("packageName", genTable.getPackageName());
|
||||
bindMap.put("moduleName", genTable.getModuleName());
|
||||
bindMap.put("subpackageName", subpackageName);
|
||||
bindMap.put("date", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"));
|
||||
bindMap.put("entityName", entityName);
|
||||
bindMap.put("tableName", genTable.getTableName());
|
||||
bindMap.put("author", genTable.getAuthor());
|
||||
String entityLowerCamel = StrUtil.lowerFirst(entityName);
|
||||
String entityKebab = StrUtil.toSymbolCase(entityName, '-');
|
||||
String entityUpperSnake = StrUtil.toSymbolCase(entityName, '_').toUpperCase();
|
||||
bindMap.put("entityLowerCamel", entityLowerCamel);
|
||||
bindMap.put("entityKebab", entityKebab);
|
||||
bindMap.put("entityUpperSnake", entityUpperSnake);
|
||||
bindMap.put("businessName", genTable.getBusinessName());
|
||||
bindMap.put("fieldConfigs", fieldConfigs);
|
||||
|
||||
boolean hasLocalDateTime = false;
|
||||
boolean hasBigDecimal = false;
|
||||
boolean hasRequiredField = false;
|
||||
|
||||
for (GenTableColumn fieldConfig : fieldConfigs) {
|
||||
|
||||
if (StrUtil.isBlank(fieldConfig.getFieldType())) {
|
||||
fieldConfig.setFieldType(JavaTypeEnum.getJavaTypeByColumnType(fieldConfig.getColumnType()));
|
||||
}
|
||||
|
||||
if ("LocalDateTime".equals(fieldConfig.getFieldType()) || "LocalDate".equals(fieldConfig.getFieldType())) {
|
||||
hasLocalDateTime = true;
|
||||
}
|
||||
if ("BigDecimal".equals(fieldConfig.getFieldType())) {
|
||||
hasBigDecimal = true;
|
||||
}
|
||||
if (ObjectUtil.equals(fieldConfig.getIsRequired(), 1)) {
|
||||
hasRequiredField = true;
|
||||
}
|
||||
fieldConfig.setTsType(JavaTypeEnum.getTsTypeByJavaType(fieldConfig.getFieldType()));
|
||||
}
|
||||
|
||||
bindMap.put("hasLocalDateTime", hasLocalDateTime);
|
||||
bindMap.put("hasBigDecimal", hasBigDecimal);
|
||||
bindMap.put("hasRequiredField", hasRequiredField);
|
||||
|
||||
TemplateEngine templateEngine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
|
||||
// 根据 ui 选择不同的前端页面模板:默认 index.vue.vm;封装版使用 index.curd.vue.vm
|
||||
String path = templatePath;
|
||||
if ("curd".equalsIgnoreCase(pageType)) {
|
||||
if (path.endsWith("index.js.vue.vm")) {
|
||||
path = path.replace("index.js.vue.vm", "index.curd.js.vue.vm");
|
||||
} else if (path.endsWith("index.vue.vm")) {
|
||||
path = path.replace("index.vue.vm", "index.curd.vue.vm");
|
||||
}
|
||||
}
|
||||
Template template = templateEngine.getTemplate(path);
|
||||
|
||||
return template.render(bindMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下载代码。
|
||||
*
|
||||
* @param tableNames 表名数组,支持多张表
|
||||
* @param ui 页面类型
|
||||
* @return zip 压缩文件字节数组
|
||||
*/
|
||||
@Override
|
||||
public byte[] downloadCode(String[] tableNames, String ui, String type) {
|
||||
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ZipOutputStream zip = new ZipOutputStream(outputStream)) {
|
||||
|
||||
// 遍历每个表名,生成对应的代码并压缩到 zip 文件中
|
||||
for (String tableName : tableNames) {
|
||||
generateAndZipCode(tableName, zip, ui, type);
|
||||
}
|
||||
// 确保所有压缩数据写入输出流,避免数据残留在内存缓冲区引发的数据不完整
|
||||
zip.finish();
|
||||
return outputStream.toByteArray();
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Error while generating zip for code download", e);
|
||||
throw new RuntimeException("Failed to generate code zip file1", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据表名生成代码并压缩到 zip 文件中。
|
||||
*
|
||||
* @param tableName 表名
|
||||
* @param zip 压缩文件输出流
|
||||
* @param ui 页面类型
|
||||
*/
|
||||
private void generateAndZipCode(String tableName, ZipOutputStream zip, String ui, String type) {
|
||||
List<CodegenPreviewVO> codePreviewList = getCodegenPreviewData(tableName, ui, type);
|
||||
|
||||
for (CodegenPreviewVO codePreview : codePreviewList) {
|
||||
String fileName = codePreview.getFileName();
|
||||
String content = codePreview.getContent();
|
||||
String path = codePreview.getPath();
|
||||
|
||||
try {
|
||||
// 创建压缩条目
|
||||
ZipEntry zipEntry = new ZipEntry(path + File.separator + fileName);
|
||||
zip.putNextEntry(zipEntry);
|
||||
|
||||
// 写入文件内容
|
||||
zip.write(content.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 关闭当前压缩条目
|
||||
zip.closeEntry();
|
||||
|
||||
} catch (IOException e) {
|
||||
log.error("Error while adding file1 {} to zip", fileName, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.youlai.boot.module.codegen.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.module.codegen.mapper.GenTableColumnMapper;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import com.youlai.boot.module.codegen.service.GenTableColumnService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 代码生成字段配置服务实现类
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GenTableColumnServiceImpl extends ServiceImpl<GenTableColumnMapper, GenTableColumn> implements GenTableColumnService {
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package com.youlai.boot.module.codegen.service.impl;
|
||||
|
||||
import cn.hutool.core.collection.CollectionUtil;
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.YouLaiBootApplication;
|
||||
import com.youlai.boot.common.enums.EnvEnum;
|
||||
import com.youlai.boot.module.codegen.enums.FormTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.JavaTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.QueryTypeEnum;
|
||||
import com.youlai.boot.core.exception.BusinessException;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.converter.CodegenConverter;
|
||||
import com.youlai.boot.module.codegen.mapper.DatabaseMapper;
|
||||
import com.youlai.boot.module.codegen.mapper.GenTableMapper;
|
||||
import com.youlai.boot.module.codegen.model.bo.ColumnMetaData;
|
||||
import com.youlai.boot.module.codegen.model.bo.TableMetaData;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import com.youlai.boot.module.codegen.model.form.GenConfigForm;
|
||||
import com.youlai.boot.module.codegen.service.GenTableService;
|
||||
import com.youlai.boot.module.codegen.service.GenTableColumnService;
|
||||
import com.youlai.boot.system.service.MenuService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 数据库服务实现类
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService {
|
||||
|
||||
private final DatabaseMapper databaseMapper;
|
||||
private final CodegenProperties codegenProperties;
|
||||
private final GenTableColumnService genTableColumnService;
|
||||
private final CodegenConverter codegenConverter;
|
||||
|
||||
@Value("${spring.profiles.active}")
|
||||
private String springProfilesActive;
|
||||
|
||||
private final MenuService menuService;
|
||||
|
||||
/**
|
||||
* 获取代码生成配置
|
||||
*
|
||||
* @param tableName 表名 eg: sys_user
|
||||
* @return 代码生成配置
|
||||
*/
|
||||
@Override
|
||||
public GenConfigForm getGenTableFormData(String tableName) {
|
||||
// 查询表生成配置
|
||||
GenTable genTable = this.getOne(
|
||||
new LambdaQueryWrapper<>(GenTable.class)
|
||||
.eq(GenTable::getTableName, tableName)
|
||||
.last("LIMIT 1")
|
||||
);
|
||||
|
||||
// 是否有代码生成配置
|
||||
boolean hasGenTable = genTable != null;
|
||||
|
||||
// 如果没有代码生成配置,则根据表的元数据生成默认配置
|
||||
if (genTable == null) {
|
||||
TableMetaData tableMetadata = databaseMapper.getTableMetadata(tableName);
|
||||
Assert.isTrue(tableMetadata != null, "未找到表元数据");
|
||||
|
||||
genTable = new GenTable();
|
||||
genTable.setTableName(tableName);
|
||||
|
||||
// 表注释作为业务名称,去掉表字 例如:用户表 -> 用户
|
||||
String tableComment = tableMetadata.getTableComment();
|
||||
if (StrUtil.isNotBlank(tableComment)) {
|
||||
genTable.setBusinessName(tableComment.replace("表", "").trim());
|
||||
}
|
||||
// 根据表名生成实体类名,支持去除前缀 例如:sys_user -> SysUser
|
||||
String removePrefix = genTable.getRemoveTablePrefix();
|
||||
String processedTable = tableName;
|
||||
if (StrUtil.isNotBlank(removePrefix) && StrUtil.startWith(tableName, removePrefix)) {
|
||||
processedTable = StrUtil.removePrefix(tableName, removePrefix);
|
||||
}
|
||||
genTable.setEntityName(StrUtil.toCamelCase(StrUtil.upperFirst(StrUtil.toCamelCase(processedTable))));
|
||||
|
||||
genTable.setPackageName(YouLaiBootApplication.class.getPackageName());
|
||||
genTable.setModuleName(codegenProperties.getDefaultConfig().getModuleName()); // 默认模块名
|
||||
genTable.setAuthor(codegenProperties.getDefaultConfig().getAuthor());
|
||||
}
|
||||
|
||||
// 根据表的列 + 已经存在的字段生成配置 得到 组合后的字段生成配置
|
||||
List<GenTableColumn> genTableColumns = new ArrayList<>();
|
||||
|
||||
// 获取表的列
|
||||
List<ColumnMetaData> tableColumns = databaseMapper.getTableColumns(tableName);
|
||||
if (CollectionUtil.isNotEmpty(tableColumns)) {
|
||||
// 查询字段生成配置
|
||||
List<GenTableColumn> fieldConfigList = genTableColumnService.list(
|
||||
new LambdaQueryWrapper<GenTableColumn>()
|
||||
.eq(GenTableColumn::getTableId, genTable.getId())
|
||||
.orderByAsc(GenTableColumn::getFieldSort)
|
||||
);
|
||||
Integer maxSort = fieldConfigList.stream()
|
||||
.map(GenTableColumn::getFieldSort)
|
||||
.filter(Objects::nonNull) // 过滤掉空值
|
||||
.max(Integer::compareTo)
|
||||
.orElse(0);
|
||||
for (ColumnMetaData tableColumn : tableColumns) {
|
||||
// 根据列名获取字段生成配置
|
||||
String columnName = tableColumn.getColumnName();
|
||||
GenTableColumn fieldConfig = fieldConfigList.stream()
|
||||
.filter(item -> StrUtil.equals(item.getColumnName(), columnName))
|
||||
.findFirst()
|
||||
.orElseGet(() -> createDefaultFieldConfig(tableColumn));
|
||||
if (fieldConfig.getFieldSort() == null) {
|
||||
fieldConfig.setFieldSort(++maxSort);
|
||||
}
|
||||
// 根据列类型设置字段类型
|
||||
String fieldType = fieldConfig.getFieldType();
|
||||
if (StrUtil.isBlank(fieldType)) {
|
||||
String javaType = JavaTypeEnum.getJavaTypeByColumnType(fieldConfig.getColumnType());
|
||||
fieldConfig.setFieldType(javaType);
|
||||
}
|
||||
// 如果没有代码生成配置,则默认展示在列表和表单
|
||||
if (!hasGenTable) {
|
||||
fieldConfig.setIsShowInList(1);
|
||||
fieldConfig.setIsShowInForm(1);
|
||||
}
|
||||
genTableColumns.add(fieldConfig);
|
||||
}
|
||||
}
|
||||
// 对 genTableColumns 按照 fieldSort 排序
|
||||
genTableColumns = genTableColumns.stream().sorted(Comparator.comparing(GenTableColumn::getFieldSort)).toList();
|
||||
GenConfigForm genConfigForm = codegenConverter.toGenConfigForm(genTable, genTableColumns);
|
||||
|
||||
genConfigForm.setFrontendAppName(codegenProperties.getFrontendAppName());
|
||||
genConfigForm.setBackendAppName(codegenProperties.getBackendAppName());
|
||||
return genConfigForm;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建默认字段配置
|
||||
*
|
||||
* @param columnMetaData 表字段元数据
|
||||
* @return
|
||||
*/
|
||||
private GenTableColumn createDefaultFieldConfig(ColumnMetaData columnMetaData) {
|
||||
GenTableColumn fieldConfig = new GenTableColumn();
|
||||
fieldConfig.setColumnName(columnMetaData.getColumnName());
|
||||
fieldConfig.setColumnType(columnMetaData.getDataType());
|
||||
fieldConfig.setFieldComment(columnMetaData.getColumnComment());
|
||||
fieldConfig.setFieldName(StrUtil.toCamelCase(columnMetaData.getColumnName()));
|
||||
fieldConfig.setIsRequired("YES".equals(columnMetaData.getIsNullable()) ? 0 : 1);
|
||||
|
||||
String columnType = StrUtil.blankToDefault(fieldConfig.getColumnType(), "").toLowerCase();
|
||||
if ("date".equals(columnType)) {
|
||||
fieldConfig.setFormType(FormTypeEnum.DATE);
|
||||
} else if ("datetime".equals(columnType) || "timestamp".equals(columnType)) {
|
||||
fieldConfig.setFormType(FormTypeEnum.DATE_TIME);
|
||||
} else {
|
||||
fieldConfig.setFormType(FormTypeEnum.INPUT);
|
||||
}
|
||||
|
||||
fieldConfig.setQueryType(QueryTypeEnum.EQ);
|
||||
fieldConfig.setMaxLength(columnMetaData.getCharacterMaximumLength());
|
||||
return fieldConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存代码生成配置
|
||||
*
|
||||
* @param formData 代码生成配置表单
|
||||
*/
|
||||
@Override
|
||||
public void saveGenConfig(GenConfigForm formData) {
|
||||
GenTable genTable = codegenConverter.toGenTable(formData);
|
||||
this.saveOrUpdate(genTable);
|
||||
|
||||
// 如果选择上级菜单且当前环境不是生产环境,则保存菜单
|
||||
Long parentMenuId = formData.getParentMenuId();
|
||||
if (parentMenuId != null && !EnvEnum.PROD.getValue().equals(springProfilesActive)) {
|
||||
menuService.addMenuForCodegen(parentMenuId, genTable);
|
||||
}
|
||||
|
||||
List<GenTableColumn> genTableColumns = codegenConverter.toGenTableColumn(formData.getFieldConfigs());
|
||||
|
||||
if (CollectionUtil.isEmpty(genTableColumns)) {
|
||||
throw new BusinessException("字段配置不能为空");
|
||||
}
|
||||
genTableColumns.forEach(genTableColumn -> {
|
||||
genTableColumn.setTableId(genTable.getId());
|
||||
});
|
||||
genTableColumnService.saveOrUpdateBatch(genTableColumns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除代码生成配置
|
||||
*
|
||||
* @param tableName 表名
|
||||
*/
|
||||
@Override
|
||||
public void deleteGenConfig(String tableName) {
|
||||
GenTable genTable = this.getOne(new LambdaQueryWrapper<GenTable>()
|
||||
.eq(GenTable::getTableName, tableName));
|
||||
|
||||
boolean result = this.remove(new LambdaQueryWrapper<GenTable>()
|
||||
.eq(GenTable::getTableName, tableName)
|
||||
);
|
||||
if (result) {
|
||||
genTableColumnService.remove(new LambdaQueryWrapper<GenTableColumn>()
|
||||
.eq(GenTableColumn::getTableId, genTable.getId())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.youlai.boot.module.file.controller;
|
||||
|
||||
import com.youlai.boot.core.web.Result;
|
||||
import com.youlai.boot.module.file.service.FileService;
|
||||
import com.youlai.boot.module.file.model.FileInfo;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 文件控制层
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 2022/10/16
|
||||
*/
|
||||
@Tag(name = "10.文件接口")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/files")
|
||||
@RequiredArgsConstructor
|
||||
public class FileController {
|
||||
|
||||
private final FileService fileService;
|
||||
|
||||
@PostMapping
|
||||
@Operation(summary = "文件上传")
|
||||
public Result<FileInfo> uploadFile(
|
||||
@Parameter(
|
||||
name = "file1",
|
||||
description = "表单文件对象",
|
||||
required = true,
|
||||
in = ParameterIn.DEFAULT,
|
||||
schema = @Schema(name = "file1", format = "binary")
|
||||
)
|
||||
@RequestPart(value = "file1") MultipartFile file
|
||||
) {
|
||||
FileInfo fileInfo = fileService.uploadFile(file);
|
||||
return Result.success(fileInfo);
|
||||
}
|
||||
|
||||
@DeleteMapping
|
||||
@Operation(summary = "文件删除")
|
||||
@SneakyThrows
|
||||
public Result<?> deleteFile(
|
||||
@Parameter(description = "文件路径") @RequestParam String filePath
|
||||
) {
|
||||
boolean result = fileService.deleteFile(filePath);
|
||||
return Result.judge(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.youlai.boot.module.file.model;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
/**
|
||||
* 文件信息对象
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@Schema(description = "文件对象")
|
||||
@Data
|
||||
public class FileInfo {
|
||||
|
||||
@Schema(description = "文件名称")
|
||||
private String name;
|
||||
|
||||
@Schema(description = "文件URL")
|
||||
private String url;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.youlai.boot.module.file.service;
|
||||
|
||||
import com.youlai.boot.module.file.model.FileInfo;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* 对象存储服务接口层
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2022/11/19
|
||||
*/
|
||||
public interface FileService {
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
* @param file 表单文件对象
|
||||
* @return 文件信息
|
||||
*/
|
||||
FileInfo uploadFile(MultipartFile file);
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
*
|
||||
* @param filePath 文件完整URL
|
||||
* @return 删除结果
|
||||
*/
|
||||
boolean deleteFile(String filePath);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.youlai.boot.module.file.service.impl;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.model.ObjectMetadata;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import com.youlai.boot.module.file.service.FileService;
|
||||
import com.youlai.boot.module.file.model.FileInfo;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Aliyun 对象存储服务类
|
||||
*
|
||||
* @author haoxr
|
||||
* @since 2.3.0
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(value = "oss.type", havingValue = "aliyun")
|
||||
@ConfigurationProperties(prefix = "oss.aliyun")
|
||||
@RequiredArgsConstructor
|
||||
@Data
|
||||
public class AliyunFileService implements FileService {
|
||||
/**
|
||||
* 服务Endpoint
|
||||
*/
|
||||
private String endpoint;
|
||||
/**
|
||||
* 访问凭据
|
||||
*/
|
||||
private String accessKeyId;
|
||||
/**
|
||||
* 凭据密钥
|
||||
*/
|
||||
private String accessKeySecret;
|
||||
/**
|
||||
* 存储桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
|
||||
private OSS aliyunOssClient;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
aliyunOssClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
|
||||
}
|
||||
|
||||
@Override
|
||||
@SneakyThrows
|
||||
public FileInfo uploadFile(MultipartFile file) {
|
||||
|
||||
// 获取文件名称
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
// 生成文件名(日期文件夹)
|
||||
String suffix = FileUtil.getSuffix(originalFilename);
|
||||
String uuid = IdUtil.simpleUUID();
|
||||
String fileName = DateUtil.format(LocalDateTime.now(), "yyyyMMdd") + "/" + uuid + "." + suffix;
|
||||
// try-with-resource 语法糖自动释放流
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
|
||||
// 设置上传文件的元信息,例如Content-Type
|
||||
ObjectMetadata metadata = new ObjectMetadata();
|
||||
metadata.setContentType(file.getContentType());
|
||||
// 创建PutObjectRequest对象,指定Bucket名称、对象名称和输入流
|
||||
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream, metadata);
|
||||
// 上传文件
|
||||
aliyunOssClient.putObject(putObjectRequest);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("文件上传失败");
|
||||
}
|
||||
// 获取文件访问路径
|
||||
String fileUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setName(originalFilename);
|
||||
fileInfo.setUrl(fileUrl);
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean deleteFile(String filePath) {
|
||||
Assert.notBlank(filePath, "删除文件路径不能为空");
|
||||
String fileHost = "https://" + bucketName + "." + endpoint; // 文件主机域名
|
||||
String fileName = filePath.substring(fileHost.length() + 1); // +1 是/占一个字符,截断左闭右开
|
||||
aliyunOssClient.deleteObject(bucketName, fileName);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.youlai.boot.module.file.service.impl;
|
||||
|
||||
import cn.hutool.core.date.DatePattern;
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import com.youlai.boot.module.file.model.FileInfo;
|
||||
import com.youlai.boot.module.file.service.FileService;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 本地存储服务类
|
||||
*
|
||||
* @author Theo
|
||||
* @since 2024-12-09 17:11
|
||||
*/
|
||||
@Data
|
||||
@Slf4j
|
||||
@Component
|
||||
@ConditionalOnProperty(value = "oss.type", havingValue = "local")
|
||||
@ConfigurationProperties(prefix = "oss.local")
|
||||
@RequiredArgsConstructor
|
||||
public class LocalFileService implements FileService {
|
||||
|
||||
@Value("${oss.local.storage-path}")
|
||||
private String storagePath;
|
||||
|
||||
/**
|
||||
* 上传文件方法
|
||||
*
|
||||
* @param file 表单文件对象
|
||||
* @return 文件信息
|
||||
*/
|
||||
@Override
|
||||
public FileInfo uploadFile(MultipartFile file) {
|
||||
// 获取文件名
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
// 获取文件后缀
|
||||
String suffix = FileUtil.getSuffix(originalFilename);
|
||||
// 生成uuid
|
||||
String fileName = IdUtil.simpleUUID()+ "." + suffix;;
|
||||
// 生成文件名(日期文件夹)
|
||||
String folder = DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN);
|
||||
String filePrefix = storagePath.endsWith(File.separator) ? storagePath : storagePath + File.separator;
|
||||
// try-with-resource 语法糖自动释放流
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
// 上传文件
|
||||
FileUtil.writeFromStream(inputStream, filePrefix + folder + File.separator + fileName);
|
||||
} catch (Exception e) {
|
||||
log.error("文件上传失败", e);
|
||||
throw new RuntimeException("文件上传失败");
|
||||
}
|
||||
// 获取文件访问路径,因为这里是本地存储,所以直接返回文件的相对路径,需要前端自行处理访问前缀
|
||||
String fileUrl = File.separator + folder + File.separator + fileName;
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setName(originalFilename);
|
||||
fileInfo.setUrl(fileUrl);
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
* @param filePath 文件完整URL
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@Override
|
||||
public boolean deleteFile(String filePath) {
|
||||
//判断文件是否为空
|
||||
if (filePath == null || filePath.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
// 判断filepath是否为文件夹
|
||||
if (FileUtil.isDirectory(storagePath + filePath)) {
|
||||
// 禁止删除文件夹
|
||||
return false;
|
||||
}
|
||||
// 删除文件
|
||||
return FileUtil.del(storagePath + filePath);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.youlai.boot.module.file.service.impl;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.youlai.boot.core.exception.BusinessException;
|
||||
import com.youlai.boot.core.web.ResultCode;
|
||||
import com.youlai.boot.module.file.model.FileInfo;
|
||||
import com.youlai.boot.module.file.service.FileService;
|
||||
import io.minio.*;
|
||||
import io.minio.http.Method;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MinIO 文件上传服务类
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 2023/6/2
|
||||
*/
|
||||
@Component
|
||||
@ConditionalOnProperty(value = "oss.type", havingValue = "minio")
|
||||
@ConfigurationProperties(prefix = "oss.minio")
|
||||
@RequiredArgsConstructor
|
||||
@Data
|
||||
@Slf4j
|
||||
public class MinioFileService implements FileService {
|
||||
|
||||
/**
|
||||
* 服务Endpoint
|
||||
*/
|
||||
private String endpoint;
|
||||
/**
|
||||
* 访问凭据
|
||||
*/
|
||||
private String accessKey;
|
||||
/**
|
||||
* 凭据密钥
|
||||
*/
|
||||
private String secretKey;
|
||||
/**
|
||||
* 存储桶名称
|
||||
*/
|
||||
private String bucketName;
|
||||
/**
|
||||
* 自定义域名
|
||||
*/
|
||||
private String customDomain;
|
||||
|
||||
private MinioClient minioClient;
|
||||
|
||||
// 依赖注入完成之后执行初始化
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
minioClient = MinioClient.builder()
|
||||
.endpoint(endpoint)
|
||||
.credentials(accessKey, secretKey)
|
||||
.build();
|
||||
// 创建存储桶(存储桶不存在)
|
||||
// createBucketIfAbsent(bucketName);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param file 表单文件对象
|
||||
* @return 文件信息
|
||||
*/
|
||||
@Override
|
||||
public FileInfo uploadFile(MultipartFile file) {
|
||||
|
||||
// 创建存储桶(存储桶不存在),如果有搭建好的minio服务,建议放在init方法中
|
||||
createBucketIfAbsent(bucketName);
|
||||
|
||||
// 文件原生名称
|
||||
String originalFilename = file.getOriginalFilename();
|
||||
// 文件后缀
|
||||
String suffix = FileUtil.getSuffix(originalFilename);
|
||||
// 文件夹名称
|
||||
String dateFolder = DateUtil.format(LocalDateTime.now(), "yyyyMMdd");
|
||||
// 文件名称
|
||||
String fileName = IdUtil.simpleUUID() + "." + suffix;
|
||||
|
||||
// try-with-resource 语法糖自动释放流
|
||||
try (InputStream inputStream = file.getInputStream()) {
|
||||
// 文件上传
|
||||
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
|
||||
.bucket(bucketName)
|
||||
.object(dateFolder + "/"+ fileName)
|
||||
.contentType(file.getContentType())
|
||||
.stream(inputStream, inputStream.available(), -1)
|
||||
.build();
|
||||
minioClient.putObject(putObjectArgs);
|
||||
|
||||
// 返回文件路径
|
||||
String fileUrl;
|
||||
// 未配置自定义域名
|
||||
if (StrUtil.isBlank(customDomain)) {
|
||||
// 获取文件URL
|
||||
GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
|
||||
.bucket(bucketName)
|
||||
.object(dateFolder + "/"+ fileName)
|
||||
.method(Method.GET)
|
||||
.build();
|
||||
|
||||
fileUrl = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
|
||||
fileUrl = fileUrl.substring(0, fileUrl.indexOf("?"));
|
||||
} else {
|
||||
// 配置自定义文件路径域名
|
||||
fileUrl = customDomain + "/"+ bucketName + "/"+ dateFolder + "/"+ fileName;
|
||||
}
|
||||
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setName(originalFilename);
|
||||
fileInfo.setUrl(fileUrl);
|
||||
return fileInfo;
|
||||
} catch (Exception e) {
|
||||
log.error("上传文件失败", e);
|
||||
throw new BusinessException(ResultCode.UPLOAD_FILE_EXCEPTION, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 删除文件
|
||||
*
|
||||
* @param filePath 文件完整路径
|
||||
* @return 是否删除成功
|
||||
*/
|
||||
@Override
|
||||
public boolean deleteFile(String filePath) {
|
||||
Assert.notBlank(filePath, "删除文件路径不能为空");
|
||||
try {
|
||||
String fileName;
|
||||
if (StrUtil.isNotBlank(customDomain)) {
|
||||
// https://oss.youlai.tech/default/20221120/test.jpg → 20221120/websocket.jpg
|
||||
fileName = filePath.substring(customDomain.length() + 1 + bucketName.length() + 1); // 两个/占了2个字符长度
|
||||
} else {
|
||||
// http://localhost:9000/default/20221120/test.jpg → 20221120/websocket.jpg
|
||||
fileName = filePath.substring(endpoint.length() + 1 + bucketName.length() + 1);
|
||||
}
|
||||
RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
|
||||
.bucket(bucketName)
|
||||
.object(fileName)
|
||||
.build();
|
||||
|
||||
minioClient.removeObject(removeObjectArgs);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.error("删除文件失败", e);
|
||||
throw new BusinessException(ResultCode.DELETE_FILE_EXCEPTION, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* PUBLIC桶策略
|
||||
* 如果不配置,则新建的存储桶默认是PRIVATE,则存储桶文件会拒绝访问 Access Denied
|
||||
*
|
||||
* @param bucketName 存储桶名称
|
||||
* @return 存储桶策略
|
||||
*/
|
||||
private static String publicBucketPolicy(String bucketName) {
|
||||
// AWS的S3存储桶策略 JSON 格式 https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/userguide/example-bucket-policies.html
|
||||
return "{\"Version\":\"2012-10-17\","
|
||||
+ "\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":[\"*\"]},"
|
||||
+ "\"Action\":[\"s3:ListBucketMultipartUploads\",\"s3:GetBucketLocation\",\"s3:ListBucket\"],"
|
||||
+ "\"Resource\":[\"arn:aws:s3:::" + bucketName + "\"]},"
|
||||
+ "{\"Effect\":\"Allow\"," + "\"Principal\":{\"AWS\":[\"*\"]},"
|
||||
+ "\"Action\":[\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\"],"
|
||||
+ "\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}";
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建存储桶(存储桶不存在)
|
||||
*
|
||||
* @param bucketName 存储桶名称
|
||||
*/
|
||||
@SneakyThrows
|
||||
private void createBucketIfAbsent(String bucketName) {
|
||||
BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
|
||||
if (!minioClient.bucketExists(bucketExistsArgs)) {
|
||||
MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
|
||||
|
||||
minioClient.makeBucket(makeBucketArgs);
|
||||
|
||||
// 设置存储桶访问权限为PUBLIC, 如果不配置,则新建的存储桶默认是PRIVATE,则存储桶文件会拒绝访问 Access Denied
|
||||
SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs
|
||||
.builder()
|
||||
.bucket(bucketName)
|
||||
.config(publicBucketPolicy(bucketName))
|
||||
.build();
|
||||
minioClient.setBucketPolicy(setBucketPolicyArgs);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user