Spring 引导不会自动创建表

Spring Boot is not creating tables automatically

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

这是我的实体

@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

}

还有我的资料库

public interface UserRepository extends JpaRepository<UserEntity, Integer> {

}

我已经添加到我的 pom.xml h2spring-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]

这是我的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');

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

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

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

提前致谢。

SQL 脚本数据源初始化 功能已在 Spring Boot 2.5 中重新设计。

By default, data.sql scripts are now run before Hibernate is initialized. This aligns the behavior of basic script-based initialization with that of Flyway and Liquibase. If you want to use data.sql to populate a schema created by Hibernate, set spring.jpa.defer-datasource-initialization to true. While mixing database initialization technologies is not recommended, this will also allow you to use a schema.sql script to build upon a Hibernate-created schema before it’s populated via data.sql.

参考

Spring Boot 2.5 Release Notes