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 org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Tag(name = "数据库表控制器", description = "数据库表信息接口") @Tag(name = "数据库表控制器", description = "数据库表信息接口")
@RestController @RestController
@ -23,11 +24,27 @@ public class TableController {
this.tableService = tableService; 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); return Result.success(list);
} }

View File

@ -13,39 +13,21 @@ import java.util.List;
@NoArgsConstructor @NoArgsConstructor
public class TableMetaData { 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 tableName;
/* 类名 */
private String className;
/* 注释内容 */ /* 注释内容 */
private String comment; private String comment;
/* 表目录 */
private String tableCat;
/* 表类型(通常是"TABLE" */
private String tableType;
/* 类名 */
private String className;
/* 列名称 */ /* 列名称 */
private List<ColumnMetaData> columns; private List<ColumnMetaData> columns;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,11 +1,8 @@
bunny: bunny:
master: master:
host: 192.168.3.137 # host: 192.168.3.137
host: localhost
port: 3306 port: 3306
database: auth_admin database: auth_admin
username: root username: root
password: "123456" 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()) { if (tables.next()) {
String remarks = tables.getString("REMARKS"); String remarks = tables.getString("REMARKS");
String tableCat = tables.getString("TABLE_CAT"); 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() tableMetaData = TableMetaData.builder()
.tableName(tableName) .tableName(tableName)
.comment(remarks) .comment(remarks)
.tableCat(tableCat) .tableCat(tableCat)
.tableSchem(tableSchem)
.tableType(tableType)
.typeCat(typeCat)
.typeSchem(typeSchem)
.typeName(typeName)
.selfReferencingColName(selfReferencingColName)
.refGeneration(refGeneration)
.build(); .build();
System.out.println(tableMetaData); System.out.println(tableMetaData);
@ -79,24 +65,10 @@ public class JDBCTest {
String tableName = tables.getString("TABLE_NAME"); String tableName = tables.getString("TABLE_NAME");
String remarks = tables.getString("REMARKS"); String remarks = tables.getString("REMARKS");
String tableCat = tables.getString("TABLE_CAT"); 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() TableMetaData tableMetaData = TableMetaData.builder()
.tableName(tableName).comment(remarks) .tableName(tableName).comment(remarks)
.tableCat(tableCat) .tableCat(tableCat)
.tableSchem(tableSchem)
.tableType(tableType)
.typeCat(typeCat)
.typeSchem(typeSchem)
.typeName(typeName)
.selfReferencingColName(selfReferencingColName)
.refGeneration(refGeneration)
.build(); .build();
list.add(tableMetaData); list.add(tableMetaData);
} }

View File

@ -2,10 +2,17 @@ package cn.bunny.utils;
import cn.bunny.dao.entity.ColumnMetaData; import cn.bunny.dao.entity.ColumnMetaData;
import cn.bunny.dao.entity.TableMetaData; import cn.bunny.dao.entity.TableMetaData;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; 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.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@SpringBootTest @SpringBootTest
@ -13,20 +20,11 @@ class DbInfoUtilTest {
String tableName = "sys_i18n"; String tableName = "sys_i18n";
// @Autowired @Autowired
// private DbInfoUtil dbInfoUtil; private DbInfoUtil dbInfoUtil;
private final DbInfoUtil dbInfoUtil; @Autowired
private DataSource dataSource;
public DbInfoUtilTest(DbInfoUtil dbInfoUtil) {
this.dbInfoUtil = dbInfoUtil;
}
@Test
void tableInfo() throws SQLException {
TableMetaData tableMetaData = dbInfoUtil.tableInfo(tableName);
System.out.println(tableMetaData);
}
@Test @Test
void columnInfo() throws SQLException { void columnInfo() throws SQLException {
@ -39,4 +37,61 @@ class DbInfoUtilTest {
TableMetaData tableMetaData = dbInfoUtil.dbInfo(tableName); TableMetaData tableMetaData = dbInfoUtil.dbInfo(tableName);
System.out.println(tableMetaData); 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);
}
}
} }