Question

I'll illustrate my issue with a contrived example to try and keep it as simple and easy to follow as possible. However my real issue is in legacy code and so I cannot change the schema or anything like that.

I have a table per class hiarachy in my code. Lets say Customer1 and Customer2. They have unique discriminator values (1 and 2 respecitivly). Each customer can may have 0 or more addresses. The addresses are stored in a single table. This table stores the reference to the customer id and the customer discriminator value. In the address mapping I have:

<any name="customer" meta-type="CustomerMetaType" id-type="long">
    <column name="customerid" not-null="true" />
    <column name="discriminator" not-null="true" />
</any>

This is fine. However in my customer1 and customer2 mappings I have:

<set name="addresses" outer-join="false">
    <key column="customerid"/>            
    <one-to-many class="Address"/>
</set>

This has the issue that loading customer1 with id 1 would pick up any addresses for customer2 with id 2. My initial attempt at a fix was to add multiple keys to the set:

<key>
    <column name="customerid"/>
    <column name="discriminator"/>
</key>

However when doing that I get the following exception:

org.hibernate.MappingException: Foreign key must have same number of columns as the referenced primary key)

Does anyone have a solution to this. Is there a way of mapping the descriminator to the class as some sort of virtual composite key? Or is there something else I can do with the set mapping to restrict it to the specific customer table?

Was it helpful?

Solution

each customer mapping needs a where condition

<set name="addresses" outer-join="false" where="discriminator='customer1'">
    <key column="customerid"/>            
    <one-to-many class="Address"/>
</set>

<set name="addresses" outer-join="false" where="discriminator='customer2'">
    <key column="customerid"/>            
    <one-to-many class="Address"/>
</set>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top