How to configure a composite foreign key in Hibernate (Tools) 3.0

The scenario of this tutorial is: we have a table with a foreign key, that reference to a composite primary key of another table. Probably a Legacy database scenario… These constraints are only logical defined. Suppose we have 2 tables. USERS and ORDERS with a one-to-many relationship. But USERS has a composite primary key: zipCode and birthDate.

Is not possible to generate the many-to-one in the HBM.XML with Hibernate Tools, because the relationship is not phisical, and with the currently DTD, we might configure a foreign-key with at least one attribute. In fact, in the hibernate-reveng.xml we can write:


<table name="ORDERS">
<primary-key>
<generator class="assigned" />
<key-column name="ID_ORDER"/>
</primary-key>


<foreign-key
constraint-name="SELLER"
foreign-schema="SCHEMA"
foreign-table="USERS">
<column-ref local-column="ID_USER" foreign-column="ID"/>
<many-to-one property="ID_USER" exclude="false" />
<set property="ORDERS"/>
</foreign-key>
</table>

But, if an USER has a composite key, you can’t configure multiple property in the many-to-one tag. In this case, the step are: one, generate HBM.XML with hbm2hbmxml ant task with a jdbconfiguration:


<hibernatetool destdir="${build.dir}/generated">
<jdbcconfiguration configurationfile="hibernate.cfg.xml"
revengfile="hibernate.reveng.xml">
</jdbcconfiguration>

and:

<hbm2hbmxml />
</hibernatetool>

Two, modify the hbm generated, and add manually the composite foreign key and the many-to-one relationship. In the ORDERS:


<many-to-one name="seller" class="User">
<column name="zipCode"/>
<column name="birthDate"/>
</many-to-one>

In the USERS hbm instead:

<set name="allOrders" inverse="true">
<key>
<column name="zipCode"/>
<column name="birthDate"/>
</key>
<one-to-many class="Orders"/>
</set>

Naturally in USERS we have:

<composite-id name="id" class="UsersId">
<key-property name="zipCode">
<column name="ZIP_CODE" />
</key-property>


<key-property name="birthDate">
<column name="BIRTH_DATE" />
</key-property>
</composite-id>

In the last step we can launch the hbm2java ant task for the pojo generation.

<hibernatetool destdir="${build.dir}/generated">
<configuration configurationfile="hibernate.cfg.xml" />
<hbm2java/>
</hibernatetool>

That’s all!

One Response to “How to configure a composite foreign key in Hibernate (Tools) 3.0”

  1. Your Cool Button site is great but when I use a comma it adds a bracket to the button. Example, What’s New creates a button, Whats/’s New.

    Tim

Leave a Reply