fix: 使用Spring Boot原生sql.init自动建表
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Agent
2026-03-24 14:19:08 +00:00
parent e09440ba63
commit 8435048156
3 changed files with 32 additions and 101 deletions

View File

@@ -1,68 +0,0 @@
package com.example.building.config;
import com.example.building.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
/**
* 数据库初始化组件
* 启动时自动执行 SQL 脚本建表
*/
@Component
public class DatabaseInitRunner implements CommandLineRunner {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void run(String... args) throws Exception {
try {
// 检查表是否存在
Integer count = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_name = 'users'",
Integer.class
);
if (count == null || count == 0) {
System.out.println("=== 初始化数据库表结构 ===");
executeSqlScript("sql/init.sql");
System.out.println("=== 数据库初始化完成 ===");
}
} catch (Exception e) {
System.out.println("数据库初始化跳过: " + e.getMessage());
}
}
private void executeSqlScript(String scriptPath) {
try {
ClassPathResource resource = new ClassPathResource(scriptPath);
String sql = new BufferedReader(
new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)
).lines().collect(Collectors.joining("\n"));
// 按分号分割执行
String[] statements = sql.split(";");
for (String stmt : statements) {
String trimmed = stmt.trim();
if (!trimmed.isEmpty() && !trimmed.startsWith("--")) {
try {
jdbcTemplate.execute(trimmed);
} catch (Exception e) {
// 忽略单个语句错误(如主键重复)
System.out.println("执行SQL跳过: " + e.getMessage());
}
}
}
} catch (Exception e) {
System.err.println("执行SQL脚本失败: " + e.getMessage());
}
}
}