在基於 Spring + Hibernate + Struts2 的 SSH 整合專案中,嘗試儲存回覆(Revert)實體時,伺服器拋出 HTTP 500 錯誤,堆疊追蹤顯示:
org.hibernate.MappingException: Unknown entity: com.ssh.domain.Revert
異常鏈路從 ArticleAction.revertArticle 經由 Service、DAO 層最終在 HibernateTemplate.save() 觸發,根因是 SessionFactoryImpl.getEntityPersister() 找不到對應的實體映射資訊。
最常見原因是 Revert 類雖然存在於 com.ssh.domain 包下,但未在 Hibernate 設定檔(hibernate.cfg.xml 或 Spring 的 LocalSessionFactoryBean)中註冊映射檔(.hbm.xml)或掃描註解。
.hbm.xml:檢查 mappingResources 或 mappingLocations 是否包含 com/ssh/domain/Revert.hbm.xmlpackagesToScan 涵蓋 com.ssh.domain@Entity 註解若採用 JPA 註解方式,Revert 類必須標註 @Entity,否則 Hibernate 不會將其視為持久化實體。
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingLocations">
<list>
<value>classpath:com/ssh/domain/*.hbm.xml</value>
</list>
</property>
<!-- 或使用註解掃描 -->
<property name="packagesToScan">
<list><value>com.ssh.domain</value></list>
</property>
</bean>
<mapping resource="com/ssh/domain/Revert.hbm.xml"/>
@Entity
@Table(name = "revert")
public class Revert implements Serializable {
@Id @GeneratedValue
private Long id;
// ... 其他欄位
}
Mapping class: com.ssh.domain.RevertUnknown entitypackagesToScan 通配掃描,減少手動維護成本