H2不使用我的data.sql文件创建架构时出错



我有一个刚开始的项目,我使用老师的模型创建了一个简单的类来映射到H2中。到目前为止,我运行了应用程序,生成了表,并尝试了一些插入命令,这些命令都很好,但当我在resources文件夹中添加data.sql时,项目拒绝生成架构。

这是我的application.properties文件:

# DATABASE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.username=sa
spring.datasource.password=

# JPA
spring.jpa.hibernate.ddl-auto=update
# H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

SuperHero.class:

@Entity
@Table(name = "super_hero")
@Data
public class SuperHero {
@Id
@Column(name="id", updatable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", nullable = false, columnDefinition = "TEXT")
private String name;
}

data.sql文件:

INSERT INTO super_hero(id, name) VALUES (1, 'Super Man');

这就是错误:

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:/Users/gabri/git/plexus-super-heroes/target/classes/data.sql]: INSERT 
INTO SUPER_HERO(id, name) VALUES (1, 'Super Man'); nested exception is 
org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "SUPER_HERO" not found; SQL statement:
INSERT INTO SUPER_HERO(id, name) VALUES (1, 'Super Man') [42102-200]

我试图将表名改为小写和大写,从头开始重新创建项目,但一直收到这个错误。

您可以将语句放在import.sql而不是data.sql中,然后重试。Hibernate使用这个文件来初始化表。

非常感谢!重命名文件后,它运行得很好。我仍然不明白为什么在另一个具有相同pom依赖关系的项目中,只有一个是针对java1.8的,而我的是针对java11的。

对我来说import.sql也很好,我尝试了更多的data.sql实验,我认为对于内存中的数据库模型,最好使用import.sql

最新更新