spring-boot - 带有 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.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。
推荐阅读
- ios - 如何在swift中根据圆圈中的百分比填充笔触颜色
- python - 单击贝宝“同意并继续”按钮时,.click() 有一半的时间起作用
- c++ - 使用自定义内核的 LIBSVM 复杂性
- c - 为什么我可以使用二维数组从 int** 转换为 int*,但不能使用指针数组?
- vue.js - Highcharts - 如何动态设置饼图的背景颜色
- spring-boot - spring JPA存储库没有将记录刷新到数据库
- jwt - DocuSign JWT 请求 invalid_grant unsupported_grant_type
- grpc - ETCD 客户端监视事件负载均衡器
- go - 使用 fyne golang 进行高效的画布刷新
- python - 使用python将单个.csv导入mysql