Hibernate:OneToMany映射不是基于PK?

时间:2010-07-21 16:36:41

标签: hibernate mapping hibernate-mapping hibernate-onetomany

我有2个实体/表。

一个是正确的实体,我们称之为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

我想将Data实体中的大陆,国家等地图映射为Map,如下所示:

@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"

我还需要能够使用用户的语言对这些“代码”的值进行文本搜索。 (例如,用法语获取country ='suisse'的所有数据!)

那么,是否可以使用不是当前实体主键的关键字段映射OneToMany集合?我需要我的大陆集合“代码表中的所有记录,其中代码=我的continentCode属性的值”。或者也许有更合适的方式来表达这种关系?

NB:不幸的是我无法更改SQL架构...

1 个答案:

答案 0 :(得分:2)

好的,我找到了解决方案。我的数据实体上的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() 

并收到字符串“Europe”:)