2010-07-21 98 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() 

和接收字符串 “欧洲” :)