代码之家  ›  专栏  ›  技术社区  ›  Pierre Henry

休眠:OneTomany映射不基于pk?

  •  2
  • Pierre Henry  · 技术社区  · 16 年前

    我有两个实体/表格。

    一个是适当的实体,我们称之为 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 “财产”。或者有一种更合适的方式来表达这种关系?

    NB:很遗憾,我无法更改SQL模式…

    1 回复  |  直到 12 年前
        1
  •  2
  •   Pierre Henry    16 年前

    好的,我找到了解决方案。我的数据实体上的OneTomany映射如下所示:

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

    我还必须绘制“控制代码”列以便它工作。我没有做,我得到了:

    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”:)