emi-le emi-le - 7 months ago 23
Java Question

Composite key including foreign key in hibernate set

I do not understand how to define a composite key, including one foreign key, inside of a set

Here my Objects:

MyObject MySubset
-------- -------------
String myId String subAttribute
String myAttribute String subValue
Set<MySubset> mySubset


I want to have two tables MyObjectTable and MySubsetTable.myId is primary key of MyObjectTable. I would like to define the FK myId and subAttribute as the composite keys of MySubsetTable.

What would the hibernate mapping of in xml look like?

<hibernate-mapping>
<class table="myObjectTable" name="MyObject">
<id name="myId">
<column name="myId"/>
</id>
<property name="myAttribute"> <column name=....> </property>
<set cascade="all, delete-orphan table="MySubsetTable" name"mySubset" ...>

<!-- How should I define my key? -->


<composite-element class="MySubset">
<property name="subAttribute"> <column name="subAttribute"/> </property>
<property name="subValue"> <column name="subValue"/> </property>
</composite-element>
</set>
</class>
</hibernate-mapping>

Answer

I solved my problem by not using a set, but a map:

<hibernate-mapping>
  <class table="myObjectTable" name="MyObject">
    <id name="myId">
      <column name="myId"/>
    </id>
    <property name="myAttribute"> <column name=....> </property>
    <map cascade="all, delete-orphan table="MySubsetTable" name"mySubset" ...>
      <key not-null="true" foreign-key="FK_MyObj" column="MyObject"/>
      <map-key type="string" column="myAttribute"/>
      <element type="string" column="myValue"/>
    </map>
  </class>
</hibernate-mapping>

Maybe this helps someone else...