views:

43

answers:

1

I have an object hierarchy that is as follows.

Party > inherited by > Organization and Person Organization > inherited by > Customer, Vendor Person > inherited by > Contact

In the database I have the following tables Party, Customer, Vendor, Contact. All of them have a corresponding row in Party table.

Contact belongs to either Vendor or Customer. I have a field on the Contact table for org_party_id. However, since the organization can be either a Customer or Vendor I need to be able to look at different tables.

Is there a way to map this in hibernate? Or, a better way to manage it in DB/ hibernate?

A: 

Create a new table called Organization with 2 fields org_party_id and org_party_type.

each org_party_id whould match match a Customer.id if the org_party_type is CUSTOMER, or a Vendor.id if the org_party_type is VENDOR.

Change the mappings of Customer and Vendor to be a Subclasses of Organization. (See the reference manual . Set org_party_type as the discriminator.

Now, set the mapping of Contact to point to Organization.

This will abstract out the organization part of Customers and Vendors, so that you can deal with them consistently. You might want to create an Organization interface in your code as well so the abstraction is consistent.

UPDATED Based on your comments, (and be rereading the question), it looks like a joined-subquery is your best bet. This would mean that you don't really need to add org_party_type, as the subclasses are joined by the ID. Like so:

   <class name="Party" table="PARTY">
            <id name="org_party_id" column="uid" type="long">
                    <generator class="hilo"/>
            </id>

            <!-- other PARTY properties -->

            <joined-subclass name="Customer" table="CUSTOMER">
                <key column="customer_id"/>
                <property name="name" type="string"/>

                <!-- other CUSTOMER properties -->

            </joined-subclass>

            <joined-subclass name="Vendor" table="VENDOR">
                <key column="vendor_id"/>
                <property name="name" type="string"/>

                <!-- other VENDOR properties -->

            </joined-subclass>
    </class>

_

Matthew Flynn
Updated - use a regular subclass rather than a joined-subclass.
Matthew Flynn
Are you suggesting that I merge the Customer and Vendor table into Organization table or create an additional Organization table? I cannot do the former. If it is the later, how is the Organization table different from the Party table. I could just add a type on the Party table.
shikarishambu
You're right--it is no different from Party. Add the type to Party and then make Vendor and Customer subclasses.
Matthew Flynn
Thinking some more about it, given that you've got Party already, you're probably best off with a joined-subclass, which would eliminate the need for a discriminator. I'll update above.
Matthew Flynn