Search code examples
javahibernatejpaormhibernate-mapping

Mapping a many-to-one relationship with a composite alternate key


I have two entities A and B with the following relationship

  1. the foreign key in A consists of two columns (composite) that don't belong to the primary key of B (alternate key);
  2. cardinality between A and B is [*] -- [0..1], that is, the foreign keys in A can be null and the many-to-one relationship is optional;
  3. the relationship is unidirectional A --> B. I want to load B eagerly in A with a join.

How can I write hibernate mappings .hbm for A and B (hibernate 3, no annotations)?


Solution

  • You could create a composite identifier property in the parent class (e.g. A):

        <properties name="ParentNaturalId">
            <property name="prop1" column="prop_1" />
            <property name="prop2" column="prop_2" />
        </properties>
    

    And the Client references the Parent through this many-to-one association:

        <many-to-one name="parent" class="B" not-null="false" not-found="ignore" property-ref="ParentNaturalId" fetch="join">
            <column name="b_prop_1" />
            <column name="b_prop_2" />
        </many-to-one>
    
    1. See the not-found="ignore" many-to-one attribute:

    not-found (optional - defaults to exception): specifies how foreign keys that reference missing rows will be handled. ignore will treat a missing row as a null association.

    1. See the fetch="join" many-to-one attribute:

    fetch (optional - defaults to select): chooses between outer-join fetching or sequential select fetching.