【发布时间】:2021-08-20 15:01:53
【问题描述】:
我有一个刚刚开始的项目,并使用我老师的模型创建了一个简单的类来映射到 H2 中。到目前为止,我运行应用程序并生成表没有问题,我尝试了一些插入命令,它们很好,但是当我在资源文件夹中添加 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]
我尝试将表名更改为小写和大写,从头开始重新创建项目,但一直收到此错误。
【问题讨论】:
-
这可能会发生,因为您的应用程序在启动时创建了表“SUPER_HERO”,并且在此之前我执行了 data.sql 脚本。所以在脚本执行的时候,这个表还没有被创建。
-
听起来很像,但让我感到困扰的是,我从老师那里得到了这个简单的示例,它使用带有 Id 和名称的 USER 表,并且在 data.sql 中运行良好我试图改变这个属性'spring .jpa.hibernate.ddl-auto=create-drop'
-
@GabrielVendramini 你去
/h2-console手动检查表是否创建?您可能会包含创建表的 data.sql 脚本吗?您是否尝试过启用日志记录?是创建了其他表还是什么都没有创建?..问题缺乏细节。
标签: java spring spring-data-jpa h2