HBM mapping between two tables with composite id

We an old application that still uses hbm.xml files, even though we are on Hibernate 5.2.16. We cannot move to annotations at this time.

We are creating an “extension” table for an existing table. The new table will use the same PK as the main table, which is also the foreign key back to the main table. The one KINK here is the fact that the PK in the extension table must also be GENERATED/FOREIGN from the PK of the main table.

We cannot find a clear example of how to map this in the HBM file (yes, it is easy using annotations but that doesn’t help us).

The table relationships are thus:

Applicant table
Id (long, identity)
Many-to-One, Optional, Lazy to Address table (discrimator)

Address table
PK is composite:
Id1 (long, foreign from Applicant, FK)
Id2 (char, discriminator)
Many-to-One, Required, Lazy to Applicant table

  One-to-One, Optional, Eager to AddressExtension table

AddressExtension table
PK is composite:
Id1 (long, foreign from Address)
Id2 (char, foreign from Address)
One-to-One (or Many-to-One, doesn’t matter), Required, Lazy, to Address table

We have tried various combinations within the composite-id tag using key-property and key-many-to-one with only marginal success. Even if the mapping actually deploys, at run time, when Hibernate tries to automatically read the AddressExtension records, other hibernate code complains that the id passed in isn’t the Address Ext Id but the Address Id (not sure where that was coming from).

Here is the mapping of the extension table. Following another issue found on the web, since Address and AddressExt both use the same “id type” class, AddressId is used in both mappings. Originally, there was an AddressExtId class but that was more problematic.

<composite-id name="id" class="AddressId" >
    
    <key-property name="applicantId" column="PERSON_ID" />
        
    <key-property name="addressType" column=" ADDRESS_TYPE" />

    <generator class="foreign">
        <param name="property">address</param>
    </generator>
    
</composite-id>

<property name="addressCategory" column="ADDRESS_CATEGORY" />

<many-to-one name="address" 
    class="Address" 
    property-ref="addressExt" />

What is the secret to mapping two tables together with the same key structure, with table B’s PK being generated from table A’s two key fields, which are also part the foreign key?

The column tag in the composite-id and many-to-one also do not allow the insert= and update= tags so we do occassionally get the duplicate field error, which cannot be corrected.

Mostly we can’t get past the FK must have the same number of columns as the PK error.