Hibernate集合映射:map属性在Entity1



我正试图将以下实体与(遗留)DB表映射,并在映射映射时遇到麻烦:

public class Configuration {
    private Long configurationId;
    private String code;
    private Long index;
    private Map<String, ConfigurationParam> configurationParams;
    ...
}

public class ConfigurationParam {
    private Long configurationId; // foreign key
    private String code;
    private String value;
    ...
}
如您所见,configuration对象包含configurationParam对象的映射。映射的键是ConfigurationParam的code属性。请注意,每个实体的属性代码彼此不相关(遗留模式:() )

hibernate映射是这样的:

<class name="Configuration" table="CONFIGURATION" dynamic-update="true">
    <id name="configurationId" column="CONFIGURATIONID">
      <generator class="assigned" />
    </id>
    <property name="configurationSetId" column="CONFIGURATIONSETID" /> 
    <property name="code" column="CODE" /> 
    <property name="index" column="INDX" /> 
    <map name="configurationParams" lazy="true" table="CONFIGURATIONPARAM"  fetch="select"  
        batch-sie="10">
        <key column="CONFIGURATIONID" />
        <map-key type="string" column="CODE"/>
        <element type="ConfigurationParam"></element>
    </map>
  </class>

<class name="ConfigurationParam" table="CONFIGURATIONPARAM" dynamic-update="true">
    <composite-id class="ConfigurationParamId" mapped="true">
        <key-property name="configurationId"/>
        <key-property name="code"/>
    </composite-id>
    <property name="configurationId" column="CONFIGURATIONID" /> 
    <property name="code" column="CODE" /> 
    <property name="value" column="VALUE" />
</class>

然而,参数没有以期望的方式加载,也不是如果我打开了eager抓取,也不是如果我试图用命名查询和join fetch configurationParams获取配置。

为什么会这样?如何正确地映射这种关联?

我已经知道问题可能是什么了,这似乎不是问题(至少单独):

  1. 两个实体都有一个名为code的属性,可能错误的一个被Hibernate用作map-key ?(当然应该使用ConfigurationParam实体的code属性)

  2. ConfigurationParam。代码不是唯一的。如您所见,ConfigurationParam的主键是一个组合。但是,由于它是一个由Configuration维护的映射,其主键是这个组合的第二部分,所以我认为这应该是可以的。

  3. ConfigurationParam。代码已经映射为实体本身的属性。可能你就不能再用它作为映射键了?但是,这个Hibernate也会告诉我,我猜?

我试图在Hibernate文档中找到答案(你知道猫之类的东西),并在这里阅读了很多其他问题,但没有找到这个特定问题的答案

好了,总算成功了。映射所属实体的映射必须像这样:

<map name="configurationParams">
    <key column="CONFIGURATIONID" />
    <map-key type="string" column="CODE"/>
    <one-to-many class="ConfigurationParam" />
</map>
元素标签似乎用于基本类型映射(例如用于Map)。如果您希望将映射实体作为映射值,则需要一个一对多标记。

hibernate文档说明:"对于基本类型或可嵌入类型的集合使用@ElementCollection"(http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html)。

虽然没有详细解释,也不是xml映射,但在解决了我的问题后,我像这样阅读它

最新更新