2015-01-07 44 views
1

我使用Hibernate和Spring Data JPA創建項目。我有一個名爲Product的超類(帶有諸如價格等字段)和一些特殊的子類,如內存,具有專用字段的處理器(對於所有類都不同)。所有產品都有獨立的桌子。Hibernate能自動識別一個實體類型嗎?

我的問題是:我能使用所有產品polimorphically - 像

productRepository.update(product) 

,並會自動休眠檢測類型OD產品(這樣它可以保存對象適當的表格)? 我用

@MappedSuperclass and @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 

註釋在我Product class - 是否足夠呢?

+0

我覺得hibernate可以使用'getClass()'來確定類,所以試試吧。 – Saif

回答

2

Hibernate繼承映射支持適用於此場景。在你的例子中,你不必打電話:

productRepository.update(product); 

除非你想附加一個分離的實體。

可能存在的問題是您需要具體的實體Spring Data存儲庫。所以你不能有productRepository,而是memoryRepositoryprocessRepository

所以,你可以得到一個Memory實體:如果修改同一個Hibernate Session附加實體

Product memory = memoryRepository.findOne(1L); 

,該dirty checking mechanism將與數據庫同步變化。

如果實體被髮送到一個HTTP會話,並重新合併在其他事務,那麼你需要使用的實際存儲庫:

memoryRepository.save(memory); 

你可以有你的資料庫擴展接口給支持實體類,然後請使用automatic scanning mechanism以獲得Map<Class, CrudRepository>,以便根據產品類型獲取關聯的存儲庫。