Hibernate - relationships using columns other than foreign primary key

16 views
Skip to first unread message

Ray

unread,
Mar 1, 2012, 1:26:28 PM3/1/12
to GreaterLansingJUG
**** Hibernate - relationships using columns other than foreign
primary key ****

Ever try to map relationship in ORM using unique non-primary codes,
instead of primary key?

Hibernate defaults to primary key, and that works so well we tend to
forget we may need to do something different.

Here are 2 mappings to do that in Hibernate, with schema:
- Major = Type of degree a college overs (BA/BS/Master for "Computer
Science (CSE)", "Civil Engineering", ...)
- Degree = awards given to individuals (1 row may be "Bachelor for
CSE for John Smith")

[Major] 1 ---> M [Degree]

Note: both of these include "column" to indicate the column in child
table (degree). If this is entered, and "property-ref" is not,
Hibernate assumes this column contains value matching the primary key
in parent table (major).

[Mapping 1-M]
=============
Parent's collection of children using "property-ref" key to specify
the Hibernate property in the parent entity containing the foreign
key.

<class name="Major" table="major">
...
<set name="degrees" inverse="true">
<key column="major_code">
<property-ref="majorCode"/>
<one-to-many class="Degree"/>
</set>
</class>

[Mapping M-1]
=============
Child entity using "property-ref" to specify the Hibernate property,
again in the parent entity, containing the foreign key.

<many-to-one
name="major"
class="Major"
column="major_code"
property-ref="majorCode">
</many-to-one>
Reply all
Reply to author
Forward
0 new messages