使用composite-id映射多对一

时间:2016-03-09 09:07:35

标签: java hibernate many-to-one composite-key hbm

我正在尝试使用多对一关系映射复合键。

如何映射一个拥有4个元素的复合id的类A和一个拥有3个元素的复合id的类B,以实现这两个具有约束的类之间的联合:

A(*)< - > (1)B?

<hibernate-mapping>
    <class name="A" table="A_TABLE" lazy="true">
        <composite-id>
            <key-property name="prop1" column="PROP1" type="string" />
            <key-property name="prop2" column="PROP2" type="long" />
            <key-property name="prop3" column="PROP3" type="long" />
            <key-property name="prop4" column="PROP4" type="integer" />
        </composite-id>
        <property name="prop10" type="string" column="PROP10" />
        ...
    </class>

    <class name="B" table="B_TABLE" lazy="false">
        <composite-id>
            <key-property name="prop1" column="PROP1" type="string" />
            <key-property name="prop2" column="PROP2" type="long" />
            <key-property name="prop3" column="PROP3" type="long" />
         </composite-id>
         <property name="prop20" type="string" column="PROP20" />
         ...
    </class>
</hibernate-mapping>

1 个答案:

答案 0 :(得分:1)

假设我有3个课程 - Other , FooBar。您可以按照以下方式创建多对一

<class name="Other" table="OTHER">
  <composite-id>
    <key-property name="id1"/> 
    <key-property name="id3"/> 
  </composite-id>
  <property name="text"/>
</class>

<class name="Foo" table="FOO">
  <composite-id>
    <key-property name="id1"/> 
    <key-property name="id2"/> 
  </composite-id>
  <property name="text"/>
</class>


<class name="Bar" table="BAR">
  <id name="id">
    <generator class="increment" />
  </id>

  <many-to-one name="foo" class="Foo" update="false" insert="false">
    <column name="FOO_ID1" />
    <column name="FOO_ID2" />
  </many-to-one>
  <many-to-one name="other" class="Other" update="false" insert="false">
    <column name="FOO_ID1" />
    <column name="FOO_ID3" />
  </many-to-one>

  <property name="text"/>
</class>