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

Hibernate配置文件hibernate.cfg.xml无法加载报错问题求助

问题根因分析
  • 首要原因是JAXB依赖缺失:JDK9及以上版本默认移除了javax.xml.bind相关模块,Hibernate解析hibernate.cfg.xml配置文件时依赖JAXB实现,缺失对应依赖就会抛出你遇到的java.security.PrivilegedActionException: java.lang.NoSuchMethodException异常,直接导致配置文件加载失败。日志中的HHH000206: hibernate.properties not found属于提示级日志,不会导致程序崩溃,属于正常提示。
  • 次要可能原因:项目构建配置问题,如果你使用的是Maven/Gradle项目,未将src/main/resources标记为资源目录,会导致编译后配置文件不会被打包到类路径下,Hibernate读取不到对应文件。
  • 兼容性问题:如果你的Hibernate版本≥6,默认已全面改用jakarta.persistence包,你代码中使用的javax.persistence注解会出现兼容问题,也会触发加载失败。
解决方案

方案1:补充JAXB依赖(适用于JDK9+、Hibernate5.x版本场景)

Maven项目在pom.xml中加入以下依赖即可:

<!-- JAXB API 依赖 -->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.1</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.3.0.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

Gradle项目在build.gradle的dependencies块中引入对应依赖即可。

方案2:修复资源目录标记(适用于资源目录未被识别场景)

IDEA环境下右键src/main/resources目录,选择「Mark Directory as」->「Resources Root」即可。如果是Maven项目默认会自动识别该目录,异常未解决时可以在pom.xml的build配置中加入如下配置确保资源被编译到类路径:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

方案3:解决Hibernate版本兼容问题

如果你使用的是Hibernate6+版本,将代码中所有javax.persistence的导入替换为jakarta.persistence,同时将配置文件中的DTD声明适配对应版本即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:24:03