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

Spring框架中H2数据库无法生成表及存储数据问题求助

问题排查与解决方案

核心问题定位

  1. Spring Boot版本与Java版本不兼容:你的pom.xml使用了Spring Boot 3.0.0,但指定Java版本为1.8。Spring Boot 3.x最低要求Java 17,这会导致JPA/Hibernate的DDL生成逻辑异常,实体类无法被正确处理。
  2. 实体类扫描范围缺失:若People实体类不在Spring Boot主启动类的同级或子包下,Spring无法自动扫描到实体,自然不会生成对应数据表。
  3. H2控制台配置冲突:修改配置后出现Whitelabel错误,大概率是控制台路径配置或依赖加载异常导致。

分步解决方案

1. 修复版本兼容问题

二选一调整版本,确保Java与Spring Boot适配:

  • 方案A(推荐):升级Java版本到17,适配Spring Boot 3.x
    <properties>
        <java.version>17</java.version>
    </properties>
    
  • 方案B:降级Spring Boot到2.x版本,适配Java 8
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.15</version>
        <relativePath/>
    </parent>
    

2. 确保实体类被正确扫描

  • 检查主启动类位置:若主类为net.javaguides.springboot.SpringbootCrudHibernateExampleApplication,People实体需放在net.javaguides.springboot或其子包(如net.javaguides.springboot.entity)下。
  • 若实体类在其他包,给主启动类添加@EntityScan注解指定扫描路径:
    @SpringBootApplication
    @EntityScan("你的实体类所在包路径")
    public class SpringbootCrudHibernateExampleApplication {
        public static void main(String[] args) {
            SpringApplication.run(SpringbootCrudHibernateExampleApplication.class, args);
        }
    }
    

3. 修正H2与JPA配置

简化application.properties,去掉冗余配置,确保DDL生成逻辑正常:

# H2数据库配置
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA/Hibernate配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

4. 验证CRUD持久化逻辑

Postman测试正常但数据未存入,需确认:

  • Service类或方法上添加了@Transactional注解,保证持久化操作在事务中执行。
  • Repository层正确继承JpaRepository<People, Integer>,且业务逻辑中调用了peopleRepository.save(people)方法。

5. 解决H2控制台Whitelabel错误

  • 启动项目后访问http://localhost:8080/h2-console(对应配置的spring.h2.console.path)。
  • 登录时JDBC URL必须与application.properties中的spring.datasource.url完全一致:jdbc:h2:mem:testdb,用户名sa,密码为空。

额外注意事项

  • pom.xml中有重复的org.jetbrains.annotations依赖,删除其中一个避免冲突。
  • 不要手动创建表,Hibernate的DDL配置会覆盖手动表结构,且实体类与手动表字段映射可能不匹配,导致无法联动。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:55:17