Spring Boot 不会自动创建表

cjg*_*gmj 4 java spring h2 spring-boot

当 Spring Boot 尝试在表中插入数据时,我遇到了错误。我正在使用 H2 和 Spring Boot 2.5.0。似乎 Spring 没有创建表。

这是我的实体

@Entity(name = "Users")
@Table(name = "users")
public class UserEntity implements Serializable {

    // Serial

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private String surname;

    private String email;

    // Getters and setters

}
Run Code Online (Sandbox Code Playgroud)

还有我的仓库

public interface UserRepository extends JpaRepository<UserEntity, Integer> {

}
Run Code Online (Sandbox Code Playgroud)

我已经添加到我的 pom.xmlh2spring-boot-starter-data-jpa.

当我以调试模式启动服务器时,出现此错误:

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:/PATH/target/classes/data.sql]: INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com'); nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Tabla "USERS" no encontrada
Table "USERS" not found; SQL statement:
INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com') [42102-200]
Run Code Online (Sandbox Code Playgroud)

这是我的data.sql

INSERT INTO users (id, name, surname, email) VALUES (1, 'Mitchell', 'Hudson', 'mitchell.hudson11@example.com');
INSERT INTO users (id, name, surname, email) VALUES (2, 'Melanie', 'Bell', 'melanie.bell51@example.com');
INSERT INTO users (id, name, surname, email) VALUES (3, 'Diane', 'Ruiz', 'diane.ruiz24@example.com');
Run Code Online (Sandbox Code Playgroud)

我在属性文件中尝试了一些配置,但无法修复错误。

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
Run Code Online (Sandbox Code Playgroud)

我可以看到插入数据的查询,但它没有生成查询来创建表,所以我认为问题出在那里。

提前致谢。

Edu*_*iek 12

SQL脚本数据源初始化功能已被重新设计,在春季启动2.5。

默认情况下,data.sql脚本现在在 Hibernate 初始化之前运行。这使基于脚本的基本初始化的行为与 Flyway 和 Liquibase 的行为保持一致。如果要用于 data.sql填充由 Hibernate 创建的模式,请设置 spring.jpa.defer-datasource-initializationtrue. 虽然不建议混合使用数据库初始化技术,但这也将允许您schema.sql在通过data.sql.

参考

Spring Boot 2.5 发行说明