首页 > 解决方案 > 带有 H2 和 data.sql 的 Spring Boot Data JPA - 未找到表

问题描述

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

应用程序.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  

数据.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-bootspring-data-jpah2

解决方案


spring.jpa.defer-datasource-initialization=true

默认情况下,data.sql 脚本现在在 Hibernate 初始化之前运行。这使基于脚本的基本初始化行为与 Flyway 和 Liquibase 的行为保持一致。

如果要使用 data.sql 填充 Hibernate 创建的模式,请将 spring.jpa.defer-datasource-initialization 设置为 true。虽然不建议混合使用数据库初始化技术,但这也将允许您在通过 data.sql 填充之前使用 schema.sql 脚本来构建 Hibernate 创建的模式。

您必须转换spring.jpa.defer-datasource-initialization为 yml。


推荐阅读