Hibernate构建SessionFactory时出现NoSuchMethodError问题求助
问题解决:Hibernate构建SessionFactory时NoSuchMethodError异常
问题根源
你遇到的NoSuchMethodError是依赖版本冲突导致的:
- 同时引入了
hibernate-annotations:3.4.0.GA(Hibernate 3.x时期的独立注解模块)和hibernate-core:5.3.31.Final-redhat-00001(Hibernate 5.x已将注解功能整合到core模块),旧模块的类与新版core的类互相干扰,导致JPAMetadataProvider找不到匹配的XMLContext构造方法。 - 项目中存在两个版本的
hibernate-commons-annotations(3.1.0.GA和5.0.5.Final-redhat-00002),进一步加剧了类加载冲突。
解决步骤
1. 移除旧版hibernate-annotations依赖
Hibernate 3.5及以后版本,注解功能已完全整合到hibernate-core中,无需单独引入旧版hibernate-annotations。直接从依赖配置(如pom.xml)中删除该依赖:
<!-- 删除以下依赖块 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.4.0.GA</version> </dependency>
2. 统一hibernate-commons-annotations版本
确保项目仅使用与hibernate-core匹配的hibernate-commons-annotations版本,手动排除其他依赖引入的旧版本:
<!-- 配置hibernate-core时排除冲突的commons-annotations --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.3.31.Final-redhat-00001</version> <exclusions> <exclusion> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> </exclusion> </exclusions> </dependency> <!-- 直接引入匹配版本的commons-annotations --> <dependency> <groupId>org.hibernate.common</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>5.0.5.Final-redhat-00002</version> </dependency>
3. 验证依赖并重新构建
执行命令确认冲突已解决:
mvn dependency:tree
确保输出中不再出现hibernate-annotations和旧版hibernate-commons-annotations,随后重新编译运行项目。
可选:升级SessionFactory构建方式(官方推荐)
你的现有代码在Hibernate 5.x中仍可运行,但官方推荐使用更现代的Bootstrap API:
import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; // 现代版SessionFactory构建代码 StandardServiceRegistry registry = new StandardServiceRegistryBuilder() .configure("hibernate.config.xml") .build(); Metadata metadata = new MetadataSources(registry) .getMetadataBuilder() .build(); sessionFactory = metadata.buildSessionFactory();
内容的提问来源于stack exchange,提问作者VMA
相关产品推荐
相关产品推荐

