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

Spring应用使用H2内存数据库报错:表未找到(数据库为空)

Spring Boot H2数据库表不存在问题解决方案

问题现象

运行Spring Boot应用时,使用H2内存数据库且未手动定义schema.sql,启动时执行data.sql或通过API添加数据均报错:

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "ITEMS" not found (this database is empty); INSERT INTO ITEMS(id, value) VALUES(1, "EXAMPLE") [42104-214]

解决步骤

1. 开启Hibernate自动建表

Spring Boot默认不会自动创建表结构,需添加配置让Hibernate根据实体类生成表:
在application.properties中新增:

spring.jpa.hibernate.ddl-auto=update
  • update:自动创建或更新表结构,保留已有数据,适合开发/生产环境
  • 开发阶段也可使用create(每次启动重建表)或create-drop(启动创建、关闭销毁)

2. 修正SQL语句的字符串引号

H2数据库要求字符串必须用单引号包裹,原data.sql中双引号会被识别为标识符,修改后:

INSERT INTO ITEMS(id, value) VALUES(1, 'EXAMPLE');

3. 完善实体类的字段访问逻辑

原Item实体类的私有字段缺少getter/setter方法,JPA无法正确映射字段,需补充:

import javax.persistence.*;

@Entity
@Table(name = "ITEMS")
public class Item {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    private String value;

    // Getter和Setter方法
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

4. 验证配置完整性

当前application.properties中的spring.jpa.defer-datasource-initialization=true已正确配置,确保data.sql在Hibernate建表后执行,无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:25:33