|
|
@@ -8,6 +8,7 @@ import org.springframework.core.io.ResourceLoader;
|
|
|
import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
import org.springframework.util.StreamUtils;
|
|
|
+import org.springframework.context.annotation.Lazy;
|
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.util.ArrayList;
|
|
|
@@ -17,6 +18,7 @@ import java.util.regex.Pattern;
|
|
|
|
|
|
@Slf4j
|
|
|
@Component
|
|
|
+@Lazy // defer init so app starts fast; migrations run once via version gate
|
|
|
public class DatabaseInitializer implements CommandLineRunner {
|
|
|
|
|
|
@Resource
|
|
|
@@ -32,19 +34,34 @@ public class DatabaseInitializer implements CommandLineRunner {
|
|
|
// 1. 检查并创建数据库
|
|
|
initializeDatabase();
|
|
|
|
|
|
- // 2. 检查并创建表
|
|
|
+ // 2. 检查并创建表(始终运行,表结构幂等)
|
|
|
initializeTables();
|
|
|
|
|
|
- // 3. 执行数据库迁移(添加新列)
|
|
|
- runMigrations();
|
|
|
-
|
|
|
- // 4. 初始化默认数据
|
|
|
- initializeDefaultData();
|
|
|
+ // 3. 迁移版本门控:只在新版本或首次运行时执行
|
|
|
+ if (!isSchemaInitialized()) {
|
|
|
+ runMigrations();
|
|
|
+ initializeDefaultData();
|
|
|
+ initFoodTables();
|
|
|
+ recordSchemaVersion(1);
|
|
|
+ log.info("数据库初始化完成!");
|
|
|
+ } else {
|
|
|
+ log.info("数据库初始化已执行,跳过(schema_version >= 1)");
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- // 5. 初始化食品相关表
|
|
|
- initFoodTables();
|
|
|
+ /** 检查 schema_version 表是否已记录初始化 */
|
|
|
+ private boolean isSchemaInitialized() {
|
|
|
+ try {
|
|
|
+ jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS schema_version (version INT PRIMARY KEY, applied_at DATETIME DEFAULT CURRENT_TIMESTAMP)");
|
|
|
+ Integer v = jdbcTemplate.queryForObject("SELECT version FROM schema_version ORDER BY version DESC LIMIT 1", Integer.class);
|
|
|
+ return v != null && v >= 1;
|
|
|
+ } catch (Exception e) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
|
|
|
- log.info("数据库初始化完成!");
|
|
|
+ private void recordSchemaVersion(int version) {
|
|
|
+ jdbcTemplate.update("INSERT INTO schema_version (version) VALUES (?)", version);
|
|
|
}
|
|
|
|
|
|
private void initializeDatabase() {
|