Spring Boot启动报错:创建entityManagerFactory Bean失败
搭建了一个仅包含配置、无业务类的基础Spring Boot项目,启动时持续报错:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory'
defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/query/BindableType
项目的build.gradle配置:
plugins { java id("org.springframework.boot") version "2.7.15" id("io.spring.dependency-management") version "1.0.15.RELEASE" } group = "com.example" version = "0.0.1-SNAPSHOT" java { sourceCompatibility = JavaVersion.VERSION_17 } repositories { mavenCentral() } dependencies { implementation("org.springframework.boot:spring-boot-starter-actuator") implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("org.springframework.boot:spring-boot-starter-security") implementation("org.springframework.boot:spring-boot-starter-validation") implementation("org.springframework.boot:spring-boot-starter-web") testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("org.springframework.security:spring-security-test") //DB implementation("org.postgresql:postgresql") implementation("org.liquibase:liquibase-core:4.23.1") implementation("com.vladmihalcea:hibernate-types-60:2.21.1") } tasks.withType<Test> { useJUnitPlatform() }
application.properties配置:
spring.main.banner-mode=off server.port=8090 # For liquibase use spring.datasource.url=jdbc:postgresql://test.com:5432/main spring.jpa.hibernate.ddl-auto= spring.liquibase.enabled=false spring.liquibase.liquibase-schema=test # PostgreSQL spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect spring.datasource.username=admin spring.datasource.password=xxx spring.jpa.properties.hibernate.default_schema=test
java.lang.NoClassDefFoundError: org/hibernate/query/BindableType 错误源于依赖版本不兼容:
- Spring Boot 2.7.x 默认集成Hibernate 5.6.x版本
- 引入的
hibernate-types-60:2.21.1是为Hibernate 6.x设计的版本,它依赖的BindableType类在Hibernate 5.x中不存在,导致entityManagerFactory初始化失败。
有两种方案可解决版本冲突问题:
方案一:降级hibernate-types到适配Hibernate 5.x的版本
将hibernate-types-60替换为适配Hibernate 5.5+的hibernate-types-55,修改build.gradle中的依赖:
// 替换原hibernate-types-60依赖 implementation("com.vladmihalcea:hibernate-types-55:2.21.1")
方案二:升级Spring Boot到支持Hibernate 6.x的版本
若需使用Hibernate 6.x,需将Spring Boot升级到3.0.x及以上(Spring Boot 3.x默认集成Hibernate 6.x),修改build.gradle的插件版本:
plugins { java id("org.springframework.boot") version "3.2.0" // 升级到Spring Boot 3.x版本 id("io.spring.dependency-management") version "1.1.4" // 适配的依赖管理版本 }
注:Spring Boot 3.x要求Java版本至少为17,你的项目已满足该条件,其他依赖会由Spring Boot依赖管理自动适配兼容版本,无需手动指定。
内容的提问来源于stack exchange,提问作者user1555190

