perf: 优化代码

This commit is contained in:
bunny 2025-04-09 21:23:26 +08:00
parent f95b65c1e0
commit dfdf9546b0
12 changed files with 190 additions and 134 deletions

View File

@ -11,6 +11,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@Tag(name = "数据库表控制器", description = "数据库表信息接口")
@RestController
@ -23,11 +24,27 @@ public class TableController {
this.tableService = tableService;
}
@Operation(summary = "数据库所有的表", description = "获取[当前/所有]数据库表")
@GetMapping("getDbTables")
public Result<List<TableInfoVo>> getDbTables(String dbName) {
List<TableInfoVo> list = tableService.getDbTables(dbName);
return Result.success(list);
}
@Operation(summary = "所有的数据库", description = "所有的数据库")
@GetMapping("getDbList")
public Result<List<TableInfoVo>> getDbList() {
List<TableInfoVo> allDb = tableService.getDbTables(null);
List<TableInfoVo> list = allDb.stream()
.collect(Collectors.groupingBy(TableInfoVo::getTableCat))
.values().stream()
.map(tableInfoVos -> {
TableInfoVo tableInfoVo = tableInfoVos.get(0);
tableInfoVo.setTableName(null);
return tableInfoVo;
}).toList();
@Operation(summary = "获取所有表", description = "获取所有表")
@GetMapping("getAllTableMetaData")
public Result<List<TableInfoVo>> getAllTableMetaData() {
List<TableInfoVo> list = tableService.getAllTableMetaData();
return Result.success(list);
}

View File

@ -13,39 +13,21 @@ import java.util.List;
@NoArgsConstructor
public class TableMetaData {
/* 表目录 */
private String tableCat;
/* 表模式可能为null */
private String tableSchem;
/* 表类型(通常是"TABLE" */
private String tableType;
/* 类型的目录可能为null */
private String typeCat;
/* 类型的模式可能为null */
private String typeSchem;
/* 类型名称可能为null */
private String typeName;
/* 自引用列名可能为null */
private String selfReferencingColName;
/* 引用生成可能为null */
private String refGeneration;
/* 表名 */
private String tableName;
/* 类名 */
private String className;
/* 注释内容 */
private String comment;
/* 表目录 */
private String tableCat;
/* 表类型(通常是"TABLE" */
private String tableType;
/* 类名 */
private String className;
/* 列名称 */
private List<ColumnMetaData> columns;
}

View File

@ -14,34 +14,16 @@ public class TableInfoVo {
/* 表目录 */
private String tableCat;
/* 表模式可能为null */
private String tableSchem;
/* 表 */
private String tableName;
/* 表类型(通常是"TABLE" */
private String tableType;
/* 类型的目录可能为null */
private String typeCat;
/* 类型的模式可能为null */
private String typeSchem;
/* 类型名称可能为null */
private String typeName;
/* 自引用列名可能为null */
private String selfReferencingColName;
/* 引用生成可能为null */
private String refGeneration;
/* 表名 */
private String tableName;
/* 注释内容 */
private String comment;
/* 类名 */
private String className;
/* 注释内容 */
private String comment;
}

View File

@ -16,11 +16,11 @@ public interface TableService {
TableInfoVo getTableMetaData(String tableName);
/**
* 获取所有
* 获取所有数据库
*
* @return 所有表信息
*/
List<TableInfoVo> getAllTableMetaData();
List<TableInfoVo> getDbTables(String tableName);
/**
* 获取列属性

View File

@ -38,14 +38,15 @@ public class TableServiceImpl implements TableService {
}
/**
* 获取所有表
* 获取[当前/所有]数据库
*
* @return 所有表信息
*/
@SneakyThrows
@Override
public List<TableInfoVo> getAllTableMetaData() {
List<TableMetaData> allTableInfo = dbInfoUtil.getAllTableInfo();
public List<TableInfoVo> getDbTables(String dbName) {
// 当前数据库数据库所有的表
List<TableMetaData> allTableInfo = dbInfoUtil.getDbTableList(dbName);
return allTableInfo.stream().map(tableMetaData -> {
TableInfoVo tableInfoVo = new TableInfoVo();
@ -56,7 +57,7 @@ public class TableServiceImpl implements TableService {
}
/**
* 获取列属性
* 获取当前表的列属性
*
* @param tableName 表名称
* @return 当前表所有的列内容

View File

@ -63,6 +63,7 @@ public class VmsServiceImpl implements VmsService {
// 数据库sql列
context.put("baseColumnList", String.join(",", list));
// 生成模板
VmsUtil.commonVms(writer, context, "vms/" + path, dto);
return GeneratorVo.builder()
@ -82,9 +83,8 @@ public class VmsServiceImpl implements VmsService {
@SneakyThrows
@Override
public Map<String, List<VmsPathVo>> getVmsPathList() {
List<String> vmsRelativeFiles;
vmsRelativeFiles = ResourceFileUtil.getRelativeFiles("vms");
// 读取当前项目中所有的 vm 模板发给前端
List<String> vmsRelativeFiles = ResourceFileUtil.getRelativeFiles("vms");
return vmsRelativeFiles.stream().map(vmFile -> {
String[] filepathList = vmFile.split("/");

View File

@ -31,31 +31,47 @@ public class DbInfoUtil {
* @return 主键列名的集合
*/
public Set<String> getPrimaryKeyColumns(String tableName) throws SQLException {
// 主键的key
Set<String> primaryKeys = new HashSet<>();
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
// 当前表的主键
ResultSet pkResultSet = metaData.getPrimaryKeys(null, null, tableName);
while (pkResultSet.next()) {
primaryKeys.add(pkResultSet.getString("COLUMN_NAME").toLowerCase());
// 列字段
String columnName = pkResultSet.getString("COLUMN_NAME").toLowerCase();
primaryKeys.add(columnName);
}
return primaryKeys;
}
}
public List<TableMetaData> getAllTableInfo() throws SQLException {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
ResultSet tables = metaData.getTables(null, null, "%", new String[]{"TABLE"});
/**
* 获取数据库中所有的表
*
* @param dbName 数据库名称如果不传为数据库中所有的表
* @return 当前/所有 的数据库表
*/
public List<TableMetaData> getDbTableList(String dbName) throws SQLException {
// 所有的表属性
List<TableMetaData> list = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
// 当前数据库中所有的表
ResultSet tables = metaData.getTables(dbName, null, "%", new String[]{"TABLE"});
while (tables.next()) {
String tableName = tables.getString("TABLE_NAME");
TableMetaData tableMetaData = tableInfo(tableName);
// 表名称
dbName = tables.getString("TABLE_NAME");
// 设置表信息
TableMetaData tableMetaData = tableInfo(dbName);
list.add(tableMetaData);
}
@ -79,27 +95,20 @@ public class DbInfoUtil {
// 获取表的注释信息
if (tables.next()) {
// 备注信息
String remarks = tables.getString("REMARKS");
// 数组名称
String tableCat = tables.getString("TABLE_CAT");
String tableSchem = tables.getString("TABLE_SCHEM");
// 通常是"TABLE"
String tableType = tables.getString("TABLE_TYPE");
String typeCat = tables.getString("TYPE_CAT");
String typeSchem = tables.getString("TYPE_SCHEM");
String typeName = tables.getString("TYPE_NAME");
String selfReferencingColName = tables.getString("SELF_REFERENCING_COL_NAME");
String refGeneration = tables.getString("REF_GENERATION");
tableMetaData = TableMetaData.builder()
.tableName(tableName)
.comment(remarks)
.tableCat(tableCat)
.tableSchem(tableSchem)
.tableType(tableType)
.typeCat(typeCat)
.typeSchem(typeSchem)
.typeName(typeName)
.selfReferencingColName(selfReferencingColName)
.refGeneration(refGeneration)
.build();
} else {
throw new RuntimeException("数据表不存在");
@ -110,7 +119,7 @@ public class DbInfoUtil {
}
/**
* 数据库列信息
* 数据库列信息
*
* @param tableName 表名
* @return 列表信息
@ -119,27 +128,43 @@ public class DbInfoUtil {
public List<ColumnMetaData> columnInfo(String tableName) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
List<ColumnMetaData> columns = new ArrayList<>();
// 当前表的主键
Set<String> primaryKeyColumns = getPrimaryKeyColumns(tableName);
// 当前表的列信息
try (ResultSet columnsRs = metaData.getColumns(null, null, tableName, null)) {
while (columnsRs.next()) {
ColumnMetaData column = new ColumnMetaData();
// 列字段
String columnName = columnsRs.getString("COLUMN_NAME");
// 将当前表的列类型转成 Java 类型
String javaType = ConvertUtil.convertToJavaType(column.getJdbcType());
// 设置列字段
column.setColumnName(columnName);
// 列字段转成 下划线 -> 小驼峰
column.setFieldName(ConvertUtil.convertToFieldName(column.getColumnName()));
// 字段类型
column.setJdbcType(columnsRs.getString("TYPE_NAME"));
// 字段类型转 Java 类型
column.setJavaType(javaType);
// 字段类型转 JavaScript 类型
column.setJavascriptType(StringUtils.uncapitalize(javaType));
// 备注信息
column.setComment(columnsRs.getString("REMARKS"));
// 确保 primaryKeyColumns 不为空
if (!primaryKeyColumns.isEmpty()) {
column.setIsPrimaryKey(primaryKeyColumns.contains(columnName));
// 是否是主键
boolean isPrimaryKey = primaryKeyColumns.contains(columnName);
column.setIsPrimaryKey(isPrimaryKey);
}
columns.add(column);

View File

@ -16,6 +16,7 @@ import java.util.jar.JarFile;
import java.util.stream.Stream;
public class ResourceFileUtil {
/**
* 获取目标文件夹下所有文件完整路径
*
@ -25,6 +26,8 @@ public class ResourceFileUtil {
*/
public static List<String> getAbsoluteFiles(String dirname) throws IOException {
List<String> fileNames = new ArrayList<>();
// 加载当前类
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = classLoader.getResources(dirname);

View File

@ -13,31 +13,53 @@ import java.util.concurrent.atomic.AtomicReference;
public class VmsUtil {
/**
* 生成模板
*
* @param writer 写入字符串内容
* @param context Velocity上下文
* @param templateName 模板名称
* @param dto 类名称可以自定义格式为 xxx_xxx
*/
public static void commonVms(StringWriter writer, VelocityContext context, String templateName, VmsArgumentDto dto) {
// 类名称如果是小驼峰需要 [手写] [下划线] 之后由 [代码 -> 小驼峰/大驼峰]
String className = dto.getClassName();
// 去除表开头前缀
String tablePrefixes = dto.getTablePrefixes();
// 当前捉着
String author = dto.getAuthor();
// 每个 Controller 上的请求前缀
String requestMapping = dto.getRequestMapping();
// 表前缀 转成数组
AtomicReference<String> replaceTableName = new AtomicReference<>(className);
for (String prefix : tablePrefixes.split("[,]" )) {
replaceTableName.set(className.replace(prefix, "" ));
for (String prefix : tablePrefixes.split("[,]")) {
replaceTableName.set(className.replace(prefix, ""));
}
String date = new SimpleDateFormat(dto.getSimpleDateFormat()).format(new Date());
context.put("leftBrace", "{" );
// vm 不能直接写 `{` 需要转换下
context.put("leftBrace", "{");
// 当前日期
context.put("date", date);
// 作者名字
context.put("author", author);
// 每个 Controller 上的请求前缀
context.put("requestMapping", requestMapping);
// 将类名称转成小驼峰
context.put("classLowercaseName", ConvertUtil.convertToCamelCase(replaceTableName.get()));
// 将类名称转成大驼峰
context.put("classUppercaseName", ConvertUtil.convertToCamelCase(replaceTableName.get(), true));
Template servicePathTemplate = Velocity.getTemplate(templateName, "UTF-8" );
// Velocity 生成模板
Template servicePathTemplate = Velocity.getTemplate(templateName, "UTF-8");
servicePathTemplate.merge(context, writer);
}
}

View File

@ -1,11 +1,8 @@
bunny:
master:
host: 192.168.3.137
# host: 192.168.3.137
host: localhost
port: 3306
database: auth_admin
username: root
password: "123456"
connect:
url: jdbc:sqlite::resource:database.sqlite
username: root
password: "123456"

View File

@ -45,25 +45,11 @@ public class JDBCTest {
if (tables.next()) {
String remarks = tables.getString("REMARKS");
String tableCat = tables.getString("TABLE_CAT");
String tableSchem = tables.getString("TABLE_SCHEM");
String tableType = tables.getString("TABLE_TYPE");
String typeCat = tables.getString("TYPE_CAT");
String typeSchem = tables.getString("TYPE_SCHEM");
String typeName = tables.getString("TYPE_NAME");
String selfReferencingColName = tables.getString("SELF_REFERENCING_COL_NAME");
String refGeneration = tables.getString("REF_GENERATION");
tableMetaData = TableMetaData.builder()
.tableName(tableName)
.comment(remarks)
.tableCat(tableCat)
.tableSchem(tableSchem)
.tableType(tableType)
.typeCat(typeCat)
.typeSchem(typeSchem)
.typeName(typeName)
.selfReferencingColName(selfReferencingColName)
.refGeneration(refGeneration)
.build();
System.out.println(tableMetaData);
@ -79,24 +65,10 @@ public class JDBCTest {
String tableName = tables.getString("TABLE_NAME");
String remarks = tables.getString("REMARKS");
String tableCat = tables.getString("TABLE_CAT");
String tableSchem = tables.getString("TABLE_SCHEM");
String tableType = tables.getString("TABLE_TYPE");
String typeCat = tables.getString("TYPE_CAT");
String typeSchem = tables.getString("TYPE_SCHEM");
String typeName = tables.getString("TYPE_NAME");
String selfReferencingColName = tables.getString("SELF_REFERENCING_COL_NAME");
String refGeneration = tables.getString("REF_GENERATION");
TableMetaData tableMetaData = TableMetaData.builder()
.tableName(tableName).comment(remarks)
.tableCat(tableCat)
.tableSchem(tableSchem)
.tableType(tableType)
.typeCat(typeCat)
.typeSchem(typeSchem)
.typeName(typeName)
.selfReferencingColName(selfReferencingColName)
.refGeneration(refGeneration)
.build();
list.add(tableMetaData);
}

View File

@ -2,10 +2,17 @@ package cn.bunny.utils;
import cn.bunny.dao.entity.ColumnMetaData;
import cn.bunny.dao.entity.TableMetaData;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
@ -13,20 +20,11 @@ class DbInfoUtilTest {
String tableName = "sys_i18n";
// @Autowired
// private DbInfoUtil dbInfoUtil;
@Autowired
private DbInfoUtil dbInfoUtil;
private final DbInfoUtil dbInfoUtil;
public DbInfoUtilTest(DbInfoUtil dbInfoUtil) {
this.dbInfoUtil = dbInfoUtil;
}
@Test
void tableInfo() throws SQLException {
TableMetaData tableMetaData = dbInfoUtil.tableInfo(tableName);
System.out.println(tableMetaData);
}
@Autowired
private DataSource dataSource;
@Test
void columnInfo() throws SQLException {
@ -39,4 +37,61 @@ class DbInfoUtilTest {
TableMetaData tableMetaData = dbInfoUtil.dbInfo(tableName);
System.out.println(tableMetaData);
}
@Test
void testTableInfo() {
TableMetaData tableMetaData;
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
ResultSet tables = metaData.getTables(null, null, tableName, new String[]{"TABLE"});
// 获取表的注释信息
if (tables.next()) {
String remarks = tables.getString("REMARKS");
String tableCat = tables.getString("TABLE_CAT");
String tableSchem = tables.getString("TABLE_SCHEM");
String tableType = tables.getString("TABLE_TYPE");
String typeCat = tables.getString("TYPE_CAT");
String typeSchem = tables.getString("TYPE_SCHEM");
String typeName = tables.getString("TYPE_NAME");
String selfReferencingColName = tables.getString("SELF_REFERENCING_COL_NAME");
String refGeneration = tables.getString("REF_GENERATION");
tableMetaData = TableMetaData.builder()
.tableName(tableName)
.comment(remarks)
.tableCat(tableCat)
.tableType(tableType)
.build();
} else {
throw new RuntimeException("数据表不存在");
}
System.out.println(tableMetaData);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SneakyThrows
@Test
void getDbTableList() {
String dbName = "auth_admin";
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
ResultSet tables = metaData.getTables(dbName, null, "%", new String[]{"TABLE"});
List<String> list = new ArrayList<>();
while (tables.next()) {
dbName = tables.getString("TABLE_NAME");
list.add(dbName);
}
System.out.println(list);
}
}
}