2016-02-22 135 views
0

我有3個要素是這樣的:JPA映射鍵使用嵌套屬性

public class ItemType { 
    @Id 
    private Long id = null; 
    ... 
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "itemTypeVO") 
    @MapKey(name = "company.id") 
    private Map<Long, ItemTypePurpose> purposeHash = null; 
    ... 
} 


public class ItemTypePurpose { 
    @Id 
    private Long id = null; 
    ... 
    @ManyToOne(fetch = FetchType.LAZY, optional = false) 
    @JoinColumn(name = "idcompany") 
    private Company company = null; 
    ... 
} 

public class Company { 
    @Id 
    private Long id = null; 
    ... 
} 

我的問題是,我想公司的ID爲我的地圖內的ItemType的關鍵。

我可以編譯和部署應用程序沒有任何錯誤。可以堅持ItemType,並且一切順利到DB。但是當我把它拿回來時,Map鍵是「錯誤的」,我不知道正在使用什麼信息,但肯定它不是公司ID。也許ItemTypePurpose的ID。

公司正在被正確加載到地圖中,只是地圖關鍵是錯誤的。我嘗試谷歌,BU找不到任何東西。有沒有辦法讓JPA用這個「嵌套屬性」創建我的地圖?

*對不起我的英語,如果你明白我需要什麼,可以用英文寫一篇更好的文章來編輯我的問題。

+1

我懷疑大多數人會使用公司實例本身作爲地圖的關鍵。 – Chris

+0

可能是一個解決方案,取決於equals()和hash()實現以及在對象內部填充的數據,否則映射上的「get()」操作可能不會返回您的對象... –

回答

0

這並不完全解決問題,但現在解決我的需求。

由於公司的闕ID是ItemTypePurpose的表,我可以映射鍵更改爲:

public class ItemType { 
    @Id 
    private Long id = null; 
    ... 
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "itemTypeVO") 
    @MapKeyColumn(name = "idcompany", insertable = false, updatable = false) 
    private Map<Long, ItemTypePurpose> purposeHash = null; 
    ... 
} 

相反@MapKey的,我用@MapKeyColumn。 @MapKeyColumn(name = "idcore_company", insertable = false, updatable = false是將「關鍵信息」只讀並且避免映射衝突,因爲在ItemTypePurpose中使用相同的列來映射實體。

不完全是一個答案,但「解決」解決我的需求。如果你想要一個字段作爲地圖密鑰而不是ID,這個解決方案不會覆蓋。