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`),導致運行時找不到資源。Unknown entity。
src/main/resources/com/hibernate/Student.hbm.xml
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes><include>**/*.hbm.xml</include></includes>
</resource>
</resources>
</build>
Configuration config = new Configuration().configure(); // 載入 hibernate.cfg.xml
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(config.getProperties()).build();
SessionFactory sf = config.buildSessionFactory(registry); // 此處會檢查映射
「你是使用配置文件配置entity的,把class那一串去了就行了」—— 實際上是將映射檔正確放入 classpath 並確保 `
` 路徑匹配。
修正資源路徑後,Hibernate 即可正確識別實體類,`Session.save()` 正常運作。