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

Hibernate 5.0.6 MappingException: Unknown entity 解決 — 實體類未在配置中註冊

     編輯:程式設計綜合問答

Hibernate 5 啟動報 MappingException: Unknown entity: com.hibernate.Student,實體類已存在、映射檔 Student.hbm.xml 路徑正確,但 SessionFactory 仍找不到實體。根因:**Configuration 未正確載入映射資源**。

錯誤堆疊

Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.Student
    at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:781)
    ...
    at com.hibernateservice.StudentTest.main(StudentTest.java:33)

專案結構


src/
├── main/
│   ├── java/
│   │   ├── com/hibernate/Student.java
│   │   └── com/hibernateservice/StudentTest.java
│   └── resources/
│       ├── hibernate.cfg.xml
│       └── com/hibernate/Student.hbm.xml   ← 關鍵:需在 resources 下

根因分析

  • hibernate.cfg.xml 中配置:<mapping resource="com/hibernate/Student.hbm.xml"/>
  • 若 Student.hbm.xml 放在 src/main/java 而非 src/main/resources,Maven/Gradle **不會將其複製到 classpath** (`target/classes`),導致運行時找不到資源。
  • Hibernate 5 `Configuration.configure()` 僅從 classpath 載入資源,找不到映射檔 → 實體未註冊 → Unknown entity。

解決方案

  1. 移動映射檔至 resources 目錄 (標準做法):
    
    src/main/resources/com/hibernate/Student.hbm.xml
    
  2. 或修正建構配置複製 XML (Maven):
    <build>
      <resources>
        <resource>
          <directory>src/main/java</directory>
          <includes><include>**/*.hbm.xml</include></includes>
        </resource>
      </resources>
    </build>
    
  3. 驗證:`mvn clean compile` 後檢查 `target/classes/com/hibernate/Student.hbm.xml` 存在。

補充:Hibernate 5 原生 API 建構 SessionFactory


Configuration config = new Configuration().configure(); // 載入 hibernate.cfg.xml
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
    .applySettings(config.getProperties()).build();
SessionFactory sf = config.buildSessionFactory(registry); // 此處會檢查映射

提問者解決回饋

「你是使用配置文件配置entity的,把class那一串去了就行了」—— 實際上是將映射檔正確放入 classpath 並確保 `` 路徑匹配。

避坑清單

  • [ ] 映射檔 (`.hbm.xml`) 放在 `src/main/resources` 而非 `java` 目錄。
  • [ ] `` 路徑與 resources 下相對路徑**完全一致** (含大小寫)。
  • [ ] 實體類 `package` 聲明與映射檔 `` 一致。
  • [ ] 執行 `mvn clean compile` 而非僅 `compile`,確保資源同步。

修正資源路徑後,Hibernate 即可正確識別實體類,`Session.save()` 正常運作。

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