为什么Spring Boot不会用schema.sql和 data.sql来初始化我的PostgreSQL数据库?
我正在一个使用PostgreSQL的 Spring Boot项目中工作。我的目标是在应用启动时自动创建表并插入初始数据。
我在 application.properties 文件中有如下配置:
spring.datasource.url=jdbc:postgresql://localhost:5432/progra3db
spring.datasource.username=progra3
spring.datasource.password=progra3
spring.datasource.driver-class-name=org.postgresql.Driver
spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=none
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
我的 schema.sql 文件里有这样一张表:
CREATE TABLE IF NOT EXISTS nodes (
id BIGINT PRIMARY KEY,
code VARCHAR(50),
name VARCHAR(100),
type VARCHAR(50),
description TEXT,
parent_id BIGINT
);
我的 data.sql 文件里有这样的测试数据:
INSERT INTO nodes (id, code, name, type, description, parent_id) VALUES
(1, '1', 'Assets', 'GROUP', 'Company assets', NULL),
(2, '1.1', 'Current Assets', 'GROUP', 'Short-term assets', 1),
(3, '1.1.1', 'Cash', 'ACCOUNT', 'Cash available', 2);
当我启动应用时,项目会跑起来,但有时数据没有被插入,或者表并未按预期出现。
我尝试在 spring.jpa.hibernate.ddl-auto 之间切换为 none、update 和 create,但在使用 schema.sql 和 data.sql 时,仍然对正确的配置感到困惑。
在应用启动时,如何正确配置Spring Boot,使PostgreSQL能从SQL文件初始化模式和数据?
解决方案
自Spring Boot 3.x以来,初始化顺序发生了变化。默认情况下,Spring Boot会在Hibernate/JPA初始化之前执行脚本(schema.sql)。问题在于,如果Hibernate配置为创建或删除表,它可能会覆盖或破坏你脚本已经设置好的内容。
如果你想通过你自己的SQL脚本对表进行完全控制,并且想防止Hibernate干扰,你需要禁用其模式生成,并确保它等待脚本完成运行,你可以按如下方式修改你的.properties:
spring.jpa.hibernate.ddl-auto=none
spring.sql.init.mode=always
spring.jpa.defer-datasource-initialization=true
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。