feat: 优化代码

This commit is contained in:
bunny 2025-04-20 22:28:45 +08:00
parent 2325754ede
commit 3d3540e3e9
13 changed files with 138 additions and 142 deletions

View File

@ -7,16 +7,23 @@ import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License; import io.swagger.v3.oas.models.info.License;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.models.GroupedOpenApi; import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
@Slf4j @Slf4j
public class Knife4jConfig { public class Knife4jConfig {
@Value("${server.port}")
private String port;
@Bean @Bean
public OpenAPI openAPI() { public OpenAPI openAPI() {
String url = "http://localhost:" + port;
// 作者等信息 // 作者等信息
Contact contact = new Contact().name("Bunny").email("1319900154@qq.com").url("http://localhost:9999"); Contact contact = new Contact().name("Bunny").email("1319900154@qq.com").url(url);
// 使用协议 // 使用协议
License license = new License().name("MIT").url("https://mit-license.org"); License license = new License().name("MIT").url("https://mit-license.org");
// 相关信息 // 相关信息
@ -24,7 +31,7 @@ public class Knife4jConfig {
.contact(contact).license(license) .contact(contact).license(license)
.description("Bunny代码生成器") .description("Bunny代码生成器")
.summary("Bunny的代码生成器") .summary("Bunny的代码生成器")
.termsOfService("http://localhost:9999") .termsOfService(url)
.version("v1.0.0"); .version("v1.0.0");
return new OpenAPI().info(info).externalDocs(new ExternalDocumentation()); return new OpenAPI().info(info).externalDocs(new ExternalDocumentation());

View File

@ -6,6 +6,8 @@ import cn.bunny.dao.vo.TableInfoVo;
import cn.bunny.service.TableService; import cn.bunny.service.TableService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
@ -18,24 +20,31 @@ import java.util.stream.Collectors;
@RequestMapping("/api/table") @RequestMapping("/api/table")
public class TableController { public class TableController {
private final TableService tableService; @Value("${bunny.master.database}")
private String currentDatabase;
public TableController(TableService tableService) { @Resource
this.tableService = tableService; private TableService tableService;
@Operation(summary = "当前配置的数据库", description = "当前配置的数据库")
@GetMapping("currentDatabaseName")
public Result<String> getCurrentDatabaseName() {
return Result.success(currentDatabase);
} }
@Operation(summary = "数据库所有的表", description = "获取[当前/所有]数据库表") @Operation(summary = "数据库所有的表", description = "获取[当前/所有]数据库表")
@GetMapping("getDbTables") @GetMapping("databaseTableList")
public Result<List<TableInfoVo>> getDbTables(String dbName) { public Result<List<TableInfoVo>> databaseTableList(String dbName) {
List<TableInfoVo> list = tableService.getDbTables(dbName); List<TableInfoVo> list = tableService.databaseTableList(dbName);
return Result.success(list); return Result.success(list);
} }
@Operation(summary = "所有的数据库", description = "所有的数据库") @Operation(summary = "所有的数据库名称", description = "当前数据库所有的数据库名称")
@GetMapping("getDbList") @GetMapping("databaseList")
public Result<List<TableInfoVo>> getDbList() { public Result<List<TableInfoVo>> databaseList() {
List<TableInfoVo> allDb = tableService.getDbTables(null); List<TableInfoVo> allDb = tableService.databaseTableList(null);
// 将当前数据库表分组以数据库名称为key
List<TableInfoVo> list = allDb.stream() List<TableInfoVo> list = allDb.stream()
.collect(Collectors.groupingBy(TableInfoVo::getTableCat)) .collect(Collectors.groupingBy(TableInfoVo::getTableCat))
.values().stream() .values().stream()
@ -48,17 +57,17 @@ public class TableController {
return Result.success(list); return Result.success(list);
} }
@Operation(summary = "获取表属性", description = "获取表属性") @Operation(summary = "表属性", description = "获取当前查询表属性")
@GetMapping("getTableMetaData") @GetMapping("tableMetaData")
public Result<TableInfoVo> getTableMetaData(String tableName) { public Result<TableInfoVo> tableMetaData(String tableName) {
TableInfoVo tableMetaData = tableService.getTableMetaData(tableName); TableInfoVo tableMetaData = tableService.tableMetaData(tableName);
return Result.success(tableMetaData); return Result.success(tableMetaData);
} }
@Operation(summary = "获取列属性", description = "获取列属性") @Operation(summary = "表的列属性", description = "获取当前查询表中列属性")
@GetMapping("getColumnInfo") @GetMapping("tableColumnInfo")
public Result<List<ColumnMetaData>> getColumnInfo(String tableName) { public Result<List<ColumnMetaData>> tableColumnInfo(String tableName) {
List<ColumnMetaData> columnInfo = tableService.getColumnInfo(tableName); List<ColumnMetaData> columnInfo = tableService.tableColumnInfo(tableName);
return Result.success(columnInfo); return Result.success(columnInfo);
} }
} }

View File

@ -7,6 +7,7 @@ import cn.bunny.dao.vo.VmsPathVo;
import cn.bunny.service.VmsService; import cn.bunny.service.VmsService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -19,16 +20,13 @@ import java.util.Map;
@RequestMapping("/api/vms") @RequestMapping("/api/vms")
public class VmsController { public class VmsController {
private final VmsService vmsService; @Resource
private VmsService vmsService;
public VmsController(VmsService vmsService) {
this.vmsService = vmsService;
}
@Operation(summary = "获取vms文件路径", description = "获取所有vms下的文件路径") @Operation(summary = "获取vms文件路径", description = "获取所有vms下的文件路径")
@GetMapping("getVmsPathList") @GetMapping("vmsResourcePathList")
public Result<Map<String, List<VmsPathVo>>> getVmsPathList() { public Result<Map<String, List<VmsPathVo>>> vmsResourcePathList() {
Map<String, List<VmsPathVo>> list = vmsService.getVmsPathList(); Map<String, List<VmsPathVo>> list = vmsService.vmsResourcePathList();
return Result.success(list); return Result.success(list);
} }

View File

@ -10,7 +10,7 @@ import lombok.extern.slf4j.Slf4j;
@Getter @Getter
@ToString @ToString
@Slf4j @Slf4j
public class AuthCustomerException extends RuntimeException { public class GeneratorCodeException extends RuntimeException {
// 状态码 // 状态码
Integer code; Integer code;
@ -21,18 +21,18 @@ public class AuthCustomerException extends RuntimeException {
ResultCodeEnum resultCodeEnum; ResultCodeEnum resultCodeEnum;
public AuthCustomerException(Integer code, String message) { public GeneratorCodeException(Integer code, String message) {
super(message); super(message);
this.code = code; this.code = code;
this.message = message; this.message = message;
} }
public AuthCustomerException(String message) { public GeneratorCodeException(String message) {
super(message); super(message);
this.message = message; this.message = message;
} }
public AuthCustomerException(ResultCodeEnum codeEnum) { public GeneratorCodeException(ResultCodeEnum codeEnum) {
super(codeEnum.getMessage()); super(codeEnum.getMessage());
this.code = codeEnum.getCode(); this.code = codeEnum.getCode();
this.message = codeEnum.getMessage(); this.message = codeEnum.getMessage();

View File

@ -24,9 +24,9 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
// 自定义异常信息 // 自定义异常信息
@ExceptionHandler(AuthCustomerException.class) @ExceptionHandler(GeneratorCodeException.class)
@ResponseBody @ResponseBody
public Result<Object> exceptionHandler(AuthCustomerException exception) { public Result<Object> exceptionHandler(GeneratorCodeException exception) {
Integer code = exception.getCode() != null ? exception.getCode() : 500; Integer code = exception.getCode() != null ? exception.getCode() : 500;
return Result.error(null, code, exception.getMessage()); return Result.error(null, code, exception.getMessage());
} }
@ -50,24 +50,24 @@ public class GlobalExceptionHandler {
String dataTooLongError = "Data too long for column (.*?) at row 1"; String dataTooLongError = "Data too long for column (.*?) at row 1";
Matcher dataTooLongErrorMatcher = Pattern.compile(dataTooLongError).matcher(message); Matcher dataTooLongErrorMatcher = Pattern.compile(dataTooLongError).matcher(message);
if (dataTooLongErrorMatcher.find()) { if (dataTooLongErrorMatcher.find()) {
return Result.error(null, 500, dataTooLongErrorMatcher.group(1) + " 字段数据过大" ); return Result.error(null, 500, dataTooLongErrorMatcher.group(1) + " 字段数据过大");
} }
// 主键冲突 // 主键冲突
String primaryKeyError = "Duplicate entry '(.*?)' for key .*"; String primaryKeyError = "Duplicate entry '(.*?)' for key .*";
Matcher primaryKeyErrorMatcher = Pattern.compile(primaryKeyError).matcher(message); Matcher primaryKeyErrorMatcher = Pattern.compile(primaryKeyError).matcher(message);
if (primaryKeyErrorMatcher.find()) { if (primaryKeyErrorMatcher.find()) {
return Result.error(null, 500, "[" + primaryKeyErrorMatcher.group(1) + "]已存在" ); return Result.error(null, 500, "[" + primaryKeyErrorMatcher.group(1) + "]已存在");
} }
// corn表达式错误 // corn表达式错误
String cronExpression = "CronExpression '(.*?)' is invalid"; String cronExpression = "CronExpression '(.*?)' is invalid";
Matcher cronExpressionMatcher = Pattern.compile(cronExpression).matcher(message); Matcher cronExpressionMatcher = Pattern.compile(cronExpression).matcher(message);
if (cronExpressionMatcher.find()) { if (cronExpressionMatcher.find()) {
return Result.error(null, 500, "表达式 " + cronExpressionMatcher.group(1) + " 不合法" ); return Result.error(null, 500, "表达式 " + cronExpressionMatcher.group(1) + " 不合法");
} }
log.error("GlobalExceptionHandler===>运行时异常信息:{}" , message); log.error("GlobalExceptionHandler===>运行时异常信息:{}", message);
return Result.error(null, 500, message); return Result.error(null, 500, message);
} }
@ -76,7 +76,7 @@ public class GlobalExceptionHandler {
public Result<String> handleValidationExceptions(MethodArgumentNotValidException ex) { public Result<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
String errorMessage = ex.getBindingResult().getFieldErrors().stream() String errorMessage = ex.getBindingResult().getFieldErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage) .map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.joining(", " )); .collect(Collectors.joining(", "));
return Result.error(null, 201, errorMessage); return Result.error(null, 201, errorMessage);
} }
@ -84,7 +84,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class) @ExceptionHandler(ArithmeticException.class)
@ResponseBody @ResponseBody
public Result<Object> error(ArithmeticException exception) { public Result<Object> error(ArithmeticException exception) {
log.error("GlobalExceptionHandler===>特定异常信息:{}" , exception.getMessage()); log.error("GlobalExceptionHandler===>特定异常信息:{}", exception.getMessage());
return Result.error(null, 500, exception.getMessage()); return Result.error(null, 500, exception.getMessage());
} }
@ -93,7 +93,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(AccessDeniedException.class) @ExceptionHandler(AccessDeniedException.class)
@ResponseBody @ResponseBody
public Result<String> error(AccessDeniedException exception) throws AccessDeniedException { public Result<String> error(AccessDeniedException exception) throws AccessDeniedException {
log.error("GlobalExceptionHandler===>spring security异常{}" , exception.getMessage()); log.error("GlobalExceptionHandler===>spring security异常{}", exception.getMessage());
return Result.error(ResultCodeEnum.SERVICE_ERROR); return Result.error(ResultCodeEnum.SERVICE_ERROR);
} }
@ -102,10 +102,10 @@ public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class) @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
@ResponseBody @ResponseBody
public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) { public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException exception) {
log.error("GlobalExceptionHandler===>处理SQL异常:{}" , exception.getMessage()); log.error("GlobalExceptionHandler===>处理SQL异常:{}", exception.getMessage());
String message = exception.getMessage(); String message = exception.getMessage();
if (message.contains("Duplicate entry" )) { if (message.contains("Duplicate entry")) {
// 错误信息 // 错误信息
return Result.error(ResultCodeEnum.USER_IS_EMPTY); return Result.error(ResultCodeEnum.USER_IS_EMPTY);
} else { } else {

View File

@ -13,14 +13,14 @@ public interface TableService {
* @param tableName 表名称 * @param tableName 表名称
* @return 表属性 * @return 表属性
*/ */
TableInfoVo getTableMetaData(String tableName); TableInfoVo tableMetaData(String tableName);
/** /**
* 获取所有数据库 * 获取所有数据库
* *
* @return 所有表信息 * @return 所有表信息
*/ */
List<TableInfoVo> getDbTables(String tableName); List<TableInfoVo> databaseTableList(String tableName);
/** /**
* 获取列属性 * 获取列属性
@ -28,5 +28,5 @@ public interface TableService {
* @param tableName 表名称 * @param tableName 表名称
* @return 当前表所有的列内容 * @return 当前表所有的列内容
*/ */
List<ColumnMetaData> getColumnInfo(String tableName); List<ColumnMetaData> tableColumnInfo(String tableName);
} }

View File

@ -23,7 +23,7 @@ public interface VmsService {
* *
* @return vms下的文件路径 * @return vms下的文件路径
*/ */
Map<String, List<VmsPathVo>> getVmsPathList(); Map<String, List<VmsPathVo>> vmsResourcePathList();
/** /**
* 打包成zip下载 * 打包成zip下载

View File

@ -5,6 +5,7 @@ import cn.bunny.dao.entity.TableMetaData;
import cn.bunny.dao.vo.TableInfoVo; import cn.bunny.dao.vo.TableInfoVo;
import cn.bunny.service.TableService; import cn.bunny.service.TableService;
import cn.bunny.utils.DbInfoUtil; import cn.bunny.utils.DbInfoUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -14,11 +15,8 @@ import java.util.List;
@Service @Service
public class TableServiceImpl implements TableService { public class TableServiceImpl implements TableService {
private final DbInfoUtil dbInfoUtil; @Resource
private DbInfoUtil dbInfoUtil;
public TableServiceImpl(DbInfoUtil dbInfoUtil) {
this.dbInfoUtil = dbInfoUtil;
}
/** /**
* 获取表属性 * 获取表属性
@ -28,7 +26,7 @@ public class TableServiceImpl implements TableService {
*/ */
@SneakyThrows @SneakyThrows
@Override @Override
public TableInfoVo getTableMetaData(String tableName) { public TableInfoVo tableMetaData(String tableName) {
TableInfoVo tableInfoVo = new TableInfoVo(); TableInfoVo tableInfoVo = new TableInfoVo();
TableMetaData tableMetaData = dbInfoUtil.tableInfo(tableName); TableMetaData tableMetaData = dbInfoUtil.tableInfo(tableName);
@ -44,7 +42,7 @@ public class TableServiceImpl implements TableService {
*/ */
@SneakyThrows @SneakyThrows
@Override @Override
public List<TableInfoVo> getDbTables(String dbName) { public List<TableInfoVo> databaseTableList(String dbName) {
// 当前数据库数据库所有的表 // 当前数据库数据库所有的表
List<TableMetaData> allTableInfo = dbInfoUtil.getDbTableList(dbName); List<TableMetaData> allTableInfo = dbInfoUtil.getDbTableList(dbName);
@ -64,7 +62,7 @@ public class TableServiceImpl implements TableService {
*/ */
@SneakyThrows @SneakyThrows
@Override @Override
public List<ColumnMetaData> getColumnInfo(String tableName) { public List<ColumnMetaData> tableColumnInfo(String tableName) {
return dbInfoUtil.columnInfo(tableName); return dbInfoUtil.columnInfo(tableName);
} }
} }

View File

@ -10,8 +10,8 @@ import cn.bunny.service.VmsService;
import cn.bunny.utils.ResourceFileUtil; import cn.bunny.utils.ResourceFileUtil;
import cn.bunny.utils.VmsUtil; import cn.bunny.utils.VmsUtil;
import cn.hutool.crypto.digest.MD5; import cn.hutool.crypto.digest.MD5;
import jakarta.annotation.Resource;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.apache.velocity.VelocityContext;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@ -29,13 +29,10 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
@Service @Service
public class VmsServiceImpl implements VmsService { public class VmsServiceImpl implements VmsService {
private final TableService tableService;
public VmsServiceImpl(TableService tableService) { @Resource
this.tableService = tableService; private TableService tableService;
}
/** /**
* 生成服务端代码 * 生成服务端代码
@ -48,33 +45,12 @@ public class VmsServiceImpl implements VmsService {
String tableName = dto.getTableName(); String tableName = dto.getTableName();
return dto.getPath().stream().map(path -> { return dto.getPath().stream().map(path -> {
StringWriter writer = new StringWriter();
// 表格属性名 列信息 // 表格属性名 列信息
TableInfoVo tableMetaData = tableService.getTableMetaData(tableName); TableInfoVo tableMetaData = tableService.tableMetaData(tableName);
List<ColumnMetaData> columnInfoList = tableService.getColumnInfo(tableName).stream().distinct().toList(); List<ColumnMetaData> columnInfoList = tableService.tableColumnInfo(tableName).stream().distinct().toList();
List<String> list = columnInfoList.stream().map(ColumnMetaData::getColumnName).toList();
// 添加要生成的属性
VelocityContext context = new VelocityContext();
// 当前的表名
context.put("tableName" , tableMetaData.getTableName());
// 表字段的注释内容
context.put("comment" , dto.getComment());
// 设置包名称
context.put("package" , dto.getPackageName());
// 当前表的列信息
context.put("columnInfoList" , columnInfoList);
// 数据库sql列
context.put("baseColumnList" , String.join("," , list));
// 生成模板 // 生成模板
VmsUtil.commonVms(writer, context, "vms/" + path, dto); StringWriter writer = VmsUtil.buildGeneratorCodeTemplate(dto, path, tableMetaData, columnInfoList);
// 处理 vm 文件名 // 处理 vm 文件名
path = VmsUtil.handleVmFilename(path, dto.getClassName()); path = VmsUtil.handleVmFilename(path, dto.getClassName());
@ -95,13 +71,13 @@ public class VmsServiceImpl implements VmsService {
*/ */
@SneakyThrows @SneakyThrows
@Override @Override
public Map<String, List<VmsPathVo>> getVmsPathList() { public Map<String, List<VmsPathVo>> vmsResourcePathList() {
// 读取当前项目中所有的 vm 模板发给前端 // 读取当前项目中所有的 vm 模板发给前端
List<String> vmsRelativeFiles = ResourceFileUtil.getRelativeFiles("vms" ); List<String> vmsRelativeFiles = ResourceFileUtil.getRelativeFiles("vms");
return vmsRelativeFiles.stream().map(vmFile -> { return vmsRelativeFiles.stream().map(vmFile -> {
String[] filepathList = vmFile.split("/" ); String[] filepathList = vmFile.split("/");
String filename = filepathList[filepathList.length - 1].replace(".vm" , "" ); String filename = filepathList[filepathList.length - 1].replace(".vm", "");
return VmsPathVo.builder().name(vmFile).label(filename).type(filepathList[0]).build(); return VmsPathVo.builder().name(vmFile).label(filename).type(filepathList[0]).build();
}) })
@ -125,7 +101,7 @@ public class VmsServiceImpl implements VmsService {
// 2. 遍历并创建 // 2. 遍历并创建
generatorVoList.forEach(generatorVo -> { generatorVoList.forEach(generatorVo -> {
// zip中的路径 // zip中的路径
String path = generatorVo.getPath().replace(".vm" , "" ); String path = generatorVo.getPath().replace(".vm", "");
// zip中的文件 // zip中的文件
String code = generatorVo.getCode(); String code = generatorVo.getCode();
@ -148,14 +124,14 @@ public class VmsServiceImpl implements VmsService {
// 2.1 文件不重名 // 2.1 文件不重名
long currentTimeMillis = System.currentTimeMillis(); long currentTimeMillis = System.currentTimeMillis();
String digestHex = MD5.create().digestHex(currentTimeMillis + "" ); String digestHex = MD5.create().digestHex(currentTimeMillis + "");
// 3. 准备响应 // 3. 准备响应
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition" , "attachment; filename=" + "vms-" + digestHex + ".zip" ); headers.add("Content-Disposition", "attachment; filename=" + "vms-" + digestHex + ".zip");
headers.add("Cache-Control" , "no-cache, no-store, must-revalidate" ); headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma" , "no-cache" ); headers.add("Pragma", "no-cache");
headers.add("Expires" , "0" ); headers.add("Expires", "0");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return new ResponseEntity<>(byteArrayInputStream.readAllBytes(), headers, HttpStatus.OK); return new ResponseEntity<>(byteArrayInputStream.readAllBytes(), headers, HttpStatus.OK);

View File

@ -1,6 +1,8 @@
package cn.bunny.utils; package cn.bunny.utils;
import cn.bunny.dao.dto.VmsArgumentDto; import cn.bunny.dao.dto.VmsArgumentDto;
import cn.bunny.dao.entity.ColumnMetaData;
import cn.bunny.dao.vo.TableInfoVo;
import com.google.common.base.CaseFormat; import com.google.common.base.CaseFormat;
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -9,70 +11,77 @@ import org.apache.velocity.app.Velocity;
import java.io.StringWriter; import java.io.StringWriter;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
public class VmsUtil { public class VmsUtil {
private static final Map<String, String> TYPE_MAPPINGS = Map.of( private static final Map<String, String> TYPE_MAPPINGS = Map.of(
"controller" , "Controller" , "controller", "Controller",
"service" , "Service" , "service", "Service",
"serviceImpl" , "ServiceImpl" , "serviceImpl", "ServiceImpl",
"mapper" , "Mapper" , "mapper", "Mapper",
"resourceMapper" , "Mapper" "resourceMapper", "Mapper"
); );
/** /**
* 生成模板 * 生成模板
* *
* @param writer 写入字符串内容
* @param context Velocity上下文
* @param templateName 模板名称
* @param dto 类名称可以自定义格式为 xxx_xxx * @param dto 类名称可以自定义格式为 xxx_xxx
* @param path 当前路径
* @param tableMetaData 表属性
* @param columnInfoList 列属性数组
* @return StringWriter
*/ */
public static void commonVms(StringWriter writer, VelocityContext context, String templateName, VmsArgumentDto dto) { public static StringWriter buildGeneratorCodeTemplate(VmsArgumentDto dto, String path, TableInfoVo tableMetaData, List<ColumnMetaData> columnInfoList) {
StringWriter writer = new StringWriter();
String date = new SimpleDateFormat(dto.getSimpleDateFormat()).format(new Date());
List<String> list = columnInfoList.stream().map(ColumnMetaData::getColumnName).toList();
// 添加要生成的属性
VelocityContext context = new VelocityContext();
// 类名称如果是小驼峰需要 [手写] [下划线] 之后由 [代码 -> 小驼峰/大驼峰] // 类名称如果是小驼峰需要 [手写] [下划线] 之后由 [代码 -> 小驼峰/大驼峰]
String className = dto.getClassName(); String className = dto.getClassName();
// 去除表开头前缀 // 去除表开头前缀
String tablePrefixes = dto.getTablePrefixes(); String tablePrefixes = dto.getTablePrefixes();
// 当前捉着 // vm 不能直接写 `{` 需要转换下
String author = dto.getAuthor(); context.put("leftBrace", "{");
// 当前日期
context.put("date", date);
// 作者名字
context.put("author", dto.getAuthor());
// 每个 Controller 上的请求前缀 // 每个 Controller 上的请求前缀
String requestMapping = dto.getRequestMapping(); context.put("requestMapping", dto.getRequestMapping());
// 当前的表名
context.put("tableName", tableMetaData.getTableName());
// 表字段的注释内容
context.put("comment", dto.getComment());
// 设置包名称
context.put("package", dto.getPackageName());
// 当前表的列信息
context.put("columnInfoList", columnInfoList);
// 数据库sql列
context.put("baseColumnList", String.join(",", list));
// 表前缀 转成数组 // 表前缀 转成数组
AtomicReference<String> replaceTableName = new AtomicReference<>(className); String replaceTableName = "";
for (String prefix : tablePrefixes.split("[,]" )) { for (String prefix : tablePrefixes.split("[,]")) {
replaceTableName.set(className.replace(prefix, "" )); replaceTableName = className.replace(prefix, "");
} }
String date = new SimpleDateFormat(dto.getSimpleDateFormat()).format(new Date());
// vm 不能直接写 `{` 需要转换下
context.put("leftBrace" , "{" );
// 当前日期
context.put("date" , date);
// 作者名字
context.put("author" , author);
// 每个 Controller 上的请求前缀
context.put("requestMapping" , requestMapping);
// 将类名称转成小驼峰 // 将类名称转成小驼峰
String toCamelCase = ConvertUtil.convertToCamelCase(replaceTableName.get()); String toCamelCase = ConvertUtil.convertToCamelCase(replaceTableName);
context.put("classLowercaseName" , toCamelCase); context.put("classLowercaseName", toCamelCase);
// 将类名称转成大驼峰 // 将类名称转成大驼峰
String convertToCamelCase = ConvertUtil.convertToCamelCase(replaceTableName.get(), true); String convertToCamelCase = ConvertUtil.convertToCamelCase(replaceTableName, true);
context.put("classUppercaseName" , convertToCamelCase); context.put("classUppercaseName", convertToCamelCase);
// Velocity 生成模板 // Velocity 生成模板
Template servicePathTemplate = Velocity.getTemplate(templateName, "UTF-8" ); Template servicePathTemplate = Velocity.getTemplate("vms/" + path, "UTF-8");
servicePathTemplate.merge(context, writer); servicePathTemplate.merge(context, writer);
return writer;
} }
/** /**
@ -82,7 +91,7 @@ public class VmsUtil {
* @param className 类名 * @param className 类名
*/ */
public static String handleVmFilename(String path, String className) { public static String handleVmFilename(String path, String className) {
String[] splitPaths = path.split("/" ); String[] splitPaths = path.split("/");
int splitPathsSize = splitPaths.length - 1; int splitPathsSize = splitPaths.length - 1;
// 大驼峰名称 // 大驼峰名称
@ -92,9 +101,9 @@ public class VmsUtil {
// 当前文件名 // 当前文件名
String filename = splitPaths[splitPathsSize]; String filename = splitPaths[splitPathsSize];
filename = filename.replace(".vm" , "" ); filename = filename.replace(".vm", "");
String[] split = filename.split("\\." ); String[] split = filename.split("\\.");
// 文件名称 // 文件名称
String name = split[0]; String name = split[0];
// 文件扩展名 // 文件扩展名
@ -106,15 +115,15 @@ public class VmsUtil {
// 判断是否是 Java 或者 xml 文件 // 判断是否是 Java 或者 xml 文件
String typeMappingsFilename = TYPE_MAPPINGS.get(name); String typeMappingsFilename = TYPE_MAPPINGS.get(name);
typeMappingsFilename = typeMappingsFilename == null ? "" : typeMappingsFilename; typeMappingsFilename = typeMappingsFilename == null ? "" : typeMappingsFilename;
if (filename.contains("java" ) || filename.contains("xml" )) { if (filename.contains("java") || filename.contains("xml")) {
filename = CamelCase + typeMappingsFilename + "." + extension; filename = CamelCase + typeMappingsFilename + "." + extension;
} }
if (filename.contains("vue" ) && !filename.contains("index" )) { if (filename.contains("vue") && !filename.contains("index")) {
filename = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, camelCase) + "-" + name + "." + extension; filename = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, camelCase) + "-" + name + "." + extension;
} }
splitPaths[splitPathsSize] = filename; splitPaths[splitPathsSize] = filename;
return String.join("/" , splitPaths); return String.join("/", splitPaths);
} }
} }

View File

@ -8,7 +8,6 @@ spring:
name: generator-code name: generator-code
thymeleaf: thymeleaf:
check-template-location: false check-template-location: false
prefix: classpath:/static/
datasource: datasource:
type: com.zaxxer.hikari.HikariDataSource type: com.zaxxer.hikari.HikariDataSource

View File

@ -15,7 +15,7 @@ class VmsServiceImplTest {
@Test @Test
void getVmsPathList() throws IOException, URISyntaxException { void vmsResourcePathList() throws IOException, URISyntaxException {
List<String> vmsFiles = ResourceFileUtil.getAbsoluteFiles("vms"); List<String> vmsFiles = ResourceFileUtil.getAbsoluteFiles("vms");
System.out.println(vmsFiles); System.out.println(vmsFiles);