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

Spring Boot 3集成JPA时entityManagerFactory创建失败求助

Spring Boot 3中entityManagerFactory创建失败的解决方案

问题根源分析

  1. Hibernate版本冲突:Spring Boot 3全面切换到Jakarta EE规范(包名从javax改为jakarta),手动引入的Hibernate 5.x仍基于旧JEE规范,导致SpringHibernateJpaPersistenceProvider无法实现新的jakarta.persistence.spi.PersistenceProvider接口。
  2. PostgreSQL驱动版本过低:移除Hibernate依赖后,Spring Boot自动引入适配的Hibernate 6.x,但旧版PostgreSQL驱动(42.2.6)缺少Hibernate 6.x所需的PGInterval.getWholeSeconds()方法,引发NoSuchMethodException。

修复步骤

1. 清理依赖,移除手动添加的Hibernate包

spring-boot-starter-data-jpa已包含与当前Spring Boot版本匹配的Hibernate依赖,无需手动引入。修改build.gradle:

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.0.5'
    id 'io.spring.dependency-management' version '1.1.0'
}

group = 'my.test.rest'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.projectlombok:lombok:1.18.26'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    // 升级PostgreSQL驱动到兼容Hibernate 6.x的版本
    implementation 'org.postgresql:postgresql:42.5.4'
    // 移除手动添加的Hibernate依赖
    // implementation 'org.hibernate:hibernate-core:5.6.9.Final'
    // implementation 'org.hibernate:hibernate-entitymanager:5.6.9.Final'
}

tasks.named('test') {
    useJUnitPlatform()
}

2. 更新Hibernate方言配置

Hibernate 6.x中PostgreSQL82Dialect已过时,替换为新版方言。修改配置类中的hibernateProperties方法:

private Properties hibernateProperties() {
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "update");
    // 替换为适配Hibernate 6.x的方言
    hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    return hibernateProperties;
}

3. 可选:简化配置(利用Spring Boot自动配置)

如果没有多数据源或特殊自定义需求,Spring Boot自动配置可省去手动创建DataSource和LocalContainerEntityManagerFactoryBean的代码。只需在application.properties中配置数据库信息:

# application.properties
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/your_db_name
spring.datasource.username=your_db_user
spring.datasource.password=your_db_password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

此时可直接删除自定义的DbConfig类,由Spring Boot自动完成配置。

验证修复

重新构建并启动项目,entityManagerFactory即可正常创建,数据库操作可正常执行。

内容的提问来源于stack exchange,提问作者Vladimir.Vasiliev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:02:33