Spring 带有 H2 和 data.sql 的引导数据 JPA - Table 未找到

Spring Boot Data JPA with H2 and data.sql - Table not Found

我有一个 Spring Boot 2.5.0 项目。我将 spring-data-jap 与 h2 内存数据库一起使用。我想在启动时使用 data.sql 文件填充数据,但出现 table 未找到异常。如果我删除 data.sql 文件,我可以看到我的实体的 table 会自动创建。但是,如果我包含 data.sql 文件,我会收到错误消息,指出 table 不存在。可能是我的 sql 语法错误,我错误地配置了 h2 数据库?

applicaltion.yml

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

debug: true  

data.sql

INSERT INTO BUSINESS_SUMMARY VALUES (1, "ALM470", "B48", 3);

BusinessSummary.java实体

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
public class BusinessSummary {

    @Id
    private Long id;
    private String businessId;
    private String businessDomainId;
    private Integer cityCode;
}

BusinessSummaryRepository.java

@Repository
public interface BusinessSummaryRepository extends JpaRepository<BusinessSummary, Long> {
}

异常:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "BUSINESS_SUMMARY" not found; SQL statement:
INSERT INTO BUSINESS_SUMMARY VALUES(1, "ALM470", "B48", 3) [42102-200]
spring.jpa.defer-datasource-initialization=true

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.jpa.defer-datasource-initialization 转换为 yml。

如果您使用 hibernate 作为 JPA 实现,我认为最好的方法是使用文件 import.sql 而不是 data.sql 用于数据库初始化。

有关数据库初始化的更多信息,请参阅官方 Spring 引导文档 Database Initialization

除了defer-datasource-initialization:没错,你可能还需要

spring:
  sql:
    init:
      mode: always
spring.jpa.defer-datasource-initialization = true    
spring.sql.init.mode = always

如果仍然无效,请尝试将文件从 data.sql 重命名为 import.sql