2010-07-21 96 views
2

我有2個實體/表。休眠:OneToMany映射不基於PK?

一個是正確的實體,我們稱之爲data。它有許多包含所謂「多語言代碼」的字段。

第二個表,code,包含多種語言值本身。

下面是一些示例數據:

Data table 
id name   continentCode countryCode 
------------------------------------ 
1 Toto   EU    CH 
2 Titi   AS    CN 

Code table 
id code language text 
---------------------------- 
1 EU  EN  Europe 
2 EU  FR  Europe 
3 EU  DE  Europa 
4 CH  EN  Switzerland 
5 CH  FR  Suisse 
6 CH  DE  Schweiz 
... etc 

我想在數據實體作爲地圖的屬性各大洲地圖,國家等,這樣的:

@OneToMany() 
@MapKey(name="languageCode") 
private Map<String, Code> continents; 

,這樣我可以然後閱讀正確的語言文字那樣:

Data toto = dao.findByName("Toto"); 
String text = toto.getContries.get("FR").getText(); //--> returns "Suisse" 
String text = toto.getContries.get("EN").getText(); //--> returns "Switzerland" 

我也需要能夠使文本使用用戶的語言搜索這些「代碼」的值。 (例如,用法語獲取國家='suisse'的所有數據!)

那麼,是否可以使用不是當前實體主鍵的鍵字段映射OneToMany集合?我需要我的大陸集合「代碼表中的所有記錄代碼=我的continentCode屬性的值」。或者也許有更合適的方式來表達這種關係?

注:不幸的是我無法改變SQL模式...

回答

2

OK,我找到了解決辦法。我的數據實體上的OneToMany映射如下所示:

@OneToMany() 
@JoinColumn(name="code", referencedColumnName="continentCode", insertable=false, updatable=false) 
@MapKey(name="languageCode") 
private Map<String, AAGeoContinentThesaurusEntry> continents; 

我還必須映射continentCode列以使其工作。科幻我沒有做到這一點,我有一個:

org.hibernate.MappingException: Unable to find column with logical name: GCH_CDE_CODE_CNT in org.hibernate.mapping.Table 
(GCHDATA) and its related supertables and secondary tables 
     at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:396) 
     at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:102) 

現在我可以這樣做:

myData.getContinentCodes().get("FR").getText() 

和接收字符串 「歐洲」 :)