You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+JPA向H2数据库插入数据失败问题求助

问题解决:Spring Boot 3 + JPA + H2 执行data.sql插入数据失败

问题原因

  1. 执行顺序冲突:Spring Boot默认先执行data.sql初始化数据,再由JPA(Hibernate)创建数据库表,导致插入数据时目标表还未生成,触发Table "PERSON" not found错误。
  2. SQL语法错误:H2数据库中,双引号""用于标识表/列名,字符串值必须用单引号''包裹,你当前的SQL语句会被解析为引用名为jan的列,而非字符串值。

解决方案

1. 调整application.properties配置

添加配置项,延迟数据初始化操作到JPA建表完成之后:

# 明确指定Hibernate自动创建表(若已有默认create/update逻辑可保留)
spring.jpa.hibernate.ddl-auto=create
# 延迟数据源初始化,等待JPA完成表创建
spring.jpa.defer-datasource-initialization=true
# 允许执行data.sql完成数据初始化
spring.sql.init.mode=always

2. 修正data.sql中的SQL语句

将字符串的双引号替换为单引号:

insert into person (name) values('jan');

3. 完整配置示例

修改后的application.properties:

spring.datasource.driver-class-name = org.h2.Driver
spring.h2.console.enable=true
spring.datasource.url=jdbc:h2:mem:testdb

# 新增配置
spring.jpa.hibernate.ddl-auto=create
spring.jpa.defer-datasource-initialization=true
spring.sql.init.mode=always

补充说明

  • 关于jakarta.persistence:Spring Boot 3及以上版本全面采用Jakarta EE规范,替代了旧的Java EE(javax.persistence),你的实体类使用jakarta.persistence是完全正确的,无需切换回旧包。
  • spring.jpa.defer-datasource-initialization=true是Spring Boot 2.5+新增的配置,专门解决JPA建表与数据初始化的顺序冲突问题。

内容的提问来源于stack exchange,提问作者Jan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:25:14