Spring Boot 2.6.6升级至3.0+因Hibernate版本冲突失败怎么办?
问题根源
从报错日志可知,Hibernate Core 6.1.7.Final尝试调用org.hibernate.annotations.common.reflection.ReflectionManager.toType(XClass)方法,但该方法在当前依赖的Hibernate Commons Annotations 5.1.2.Final中不存在。这是因为Hibernate 6.x系列需要配套的Commons Annotations版本为6.x,而5.1.2是适配Hibernate 5.x的旧版本,两者API不兼容。
解决方案
1. 排除旧版本的hibernate-commons-annotations依赖
检查项目依赖树,找到引入org.hibernate.common:hibernate-commons-annotations:5.1.2.Final的第三方依赖,在pom.xml(或build.gradle)中排除该依赖,避免与Spring Boot 3.x默认的Hibernate 6.x版本冲突。
Maven示例:
<dependency> <groupId>[第三方依赖groupId]</groupId> <artifactId>[第三方依赖artifactId]</artifactId> <exclusions> <exclusion> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> </exclusion> </exclusions> </dependency>
Gradle示例:
implementation('[第三方依赖groupId]:[第三方依赖artifactId]:[版本号]') { exclude group: 'org.hibernate.common', module: 'hibernate-commons-annotations' }
2. 依赖版本交由Spring Boot Parent管理
Spring Boot 3.0.x默认集成了兼容版本的Hibernate(6.1.x系列),以及对应的org.hibernate.orm:hibernate-commons-annotations(注意groupId已从org.hibernate.common变更为org.hibernate.orm)。不要手动指定Hibernate相关依赖的版本,完全依赖Spring Boot Parent的依赖管理即可,避免版本不匹配。
3. 清理依赖缓存并重新构建
旧版本的依赖可能残存在本地仓库中,执行以下命令清理缓存并重新构建项目:
Maven:
mvn clean install -U
Gradle:
./gradlew clean build --refresh-dependencies
额外注意事项
- Spring Boot 3.x要求Java版本≥17,你当前使用的Java 19符合要求,无需调整。
- 检查Spring Data JPA等其他JPA相关依赖,确保版本与Spring Boot 3.x兼容,优先使用Spring Boot Parent管理的版本,避免手动指定旧版本。
内容的提问来源于stack exchange,提问作者E Ajh

