2.5.0升级后,SpringBoot数据源初始化错误,data.sql脚本
我有一个配置了 Spring Boot 和 Spring Data JPA 的项目。
我的项目包含以下data.sql初始化脚本(我刚刚开始开发我的应用程序,这就是我使用嵌入式 H2 数据库的原因):
INSERT INTO Project(id, name) VALUES (1, 'Project 1');
我正在定义以下实体:
@Entity
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
protected Project() {
}
public Project(String name) {
this.name = name;
}
// ...
}
我没有任何其他配置/设置。
ERROR 5520 ---[ restartedMain] o.s.boot.SpringApplication :Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/path/project/target/classes/data.sql]: INSERT INTO Project(id, name) VALUES (1, 'Project 1'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "PROJECT" not found; SQL statement:
INSERT INTO Project(id, name) VALUES (1, 'Project 1') [42102-200]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1786)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:602)
...
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of URL [file:/C:/path/project/target/classes/data.sql]: INSERT INTO Project(id, name) VALUES (1, 'Project 1'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "PROJECT" not found; SQL statement:
INSERT INTO Project(id, name) VALUES (1, 'Project 1') [42102-200]
at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:622)
at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254)
...
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "PROJECT" not found; SQL statement:
INSERT INTO Project(id, name) VALUES (1, 'Project 1') [42102-200]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:453)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
当然,在升级之前,应用程序启动得很好。
回答
TL; 博士
似乎 Spring Boot 已经修改了它使用 .sql 脚本初始化数据源的方式2.5.0。
这可以通过在项目中包含以下属性来解决:
spring:
jpa:
defer-datasource-initialization: true
说明:
在 中引入的更改中2.5.0,现在data.sql脚本似乎是在初始化 Hibernate 之前执行的:
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.5-Release-Notes#hibernate-and-datasql
并且由于我依靠 ORM 机制(即 Hibernate)从实体定义创建模式,因此在执行初始化 SQL 脚本时数据库表不存在。
THE END
二维码