tags:

views:

50

answers:

1

when should you use the class element of the composite-id ?

for example, consider this snippet :

<composite-id name="id" ***class="OrderLineId"***>
    <key-property name="lineId"/>
    <key-property name="orderId"/>
    <key-property name="customerId"/>
</composite-id>

<property name="name"/>

<many-to-one name="order" class="Order"
        insert="false" update="false">
    <column name="orderId"/>
    <column name="customerId"/>
 </many-to-one>
  ....

for example, what is the purpose of OrderLineId above ? how does it relate to other parts ?

+1  A: 

The short answer is "you shouldn't" :-)

It's generally a good idea to use a surrogate key in the first place; furthermore you'd make your mappings a lot simpler by using a single id instead of composite one. That said, there are situations (like mapping legacy schemas) when you need to use a composite key.

The above example shows how to map composite key as component. This is a better approach than using entity itself as its own key, which is what would happen if you were to map it without the class attribute on <composite-id>. The main differences are:

  1. When mapping composite key as component, you'll write a new class (OrderLineId) that would contain mapped individual key parts (lineId, orderId, customerId) as properties. When mapping composite key on entity itself your entity class (OrderLine) would have to contain those properties.
  2. In order to load OrderLine using "key as component" mapping, you'll create a new instance of OrderLineId and pass it to session.get() as key. Using "key on entity" mapping you will have to create an instance of OrderLine to load OrderLine, which is confusing at best and presents data integrity concerns at worst.
ChssPly76