首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Spring Bean 建立失敗:org.hibernate.MappingNotFoundException 解決實錄

     編輯:程式設計綜合問答

Spring 整合 Hibernate 專案啟動時拋出 Error creating bean with name 'vipService',堆疊追蹤顯示根因為 org.hibernate.MappingNotFoundException: resource: bean/program.hbm.xml not found。本文記錄排查過程與解決方案。

錯誤堆疊關鍵片段

Caused by: org.hibernate.MappingNotFoundException: resource: bean/program.hbm.xml not found
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:799)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
    ...
    at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
    at business.VipBusinessHibernate.<init>(VipBusinessHibernate.java:21)

原因分析

Hibernate 在建立 SessionFactory 時,依據配置檔(hibernate.cfg.xml)載入對映檔(.hbm.xml)。錯誤訊息明確指出:找不到 classpath 下的 bean/program.hbm.xml 資源。

常見導致原因

  1. 對映檔路徑錯誤:<mapping resource="bean/program.hbm.xml"/> 指定的相對路徑與實際檔案位置不符。
  2. 檔案未納入編譯輸出:Maven/Gradle 專案中,.hbm.xml 放置於 src/main/java 但建構工具未將非 Java 檔案複製至 target/classes。
  3. 檔案名稱大小寫不一致:Linux 伺服器區分大小寫,Program.hbm.xml ≠ program.hbm.xml。
  4. 封裝時遺漏資源檔:打包為 JAR/WAR 時未包含對映檔。

解決步驟

  1. 確認檔案實際位置:在 IDE 專案結構中找到 program.hbm.xml,記錄其相對於 src/main/resources 或 src/main/java 的路徑。
  2. 修正 mapping 資源路徑:若檔案在 src/main/resources/bean/program.hbm.xml,則配置應為 <mapping resource="bean/program.hbm.xml"/>;若在 src/main/java/com/example/bean/program.hbm.xml,則為 <mapping resource="com/example/bean/program.hbm.xml"/>。
  3. 調整建構配置(Maven 範例):
    <build>
      <resources>
        <resource>
          <directory>src/main/java</directory>
          <includes>
            <include>**/*.hbm.xml</include>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
          </includes>
        </resource>
        <resource>
          <directory>src/main/resources</directory>
        </resource>
      </resources>
    </build>
    
  4. 清理並重新建構:執行 mvn clean compile 或 IDE 的 Rebuild,確認 target/classes/bean/program.hbm.xml 存在。
  5. 驗證部署成品:解壓 WAR/JAR 檢查對映檔是否包含在內。

補充建議

  • 改用註解式對映(@Entity、@Table)可完全避免 .hbm.xml 路徑維護問題。
  • 啟動時加上 -verbose:class 或除錯 Configuration.addResource 可觀察實際載入路徑。

修正路徑並確保資源檔正確打包後,重新啟動應用程式,vipService Bean 即可順利建立,系統恢復正常。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved