Example: Various Mappings
This chapters shows off some more complex association mappings.
Employer/Employee
The following model of the relationship between Employer and
Employee uses an actual entity class (Employment)
to represent the association. This is done because there might be more than one
period of employment for the same two parties. Components are used to model monetary
values and employee names.
Heres a possible mapping document:
employer_id_seq
employment_id_seq
employee_id_seq
]]>
And heres the table schema generated by SchemaExport.
Author/Work
Consider the following model of the relationships between Work,
Author and Person. We represent the relationship
between Work and Author as a many-to-many
association. We choose to represent the relationship between Author
and Person as one-to-one association. Another possibility would be to
have Author extend Person.
The following mapping document correctly represents these relationships:
]]>
There are four tables in this mapping. works,
authors and persons hold work, author
and person data respectively. author_work is an association
table linking authors to works. Heres the table schema, as generated by
SchemaExport.
Customer/Order/Product
Now consider a model of the relationships between Customer,
Order and LineItem and Product.
There is a one-to-many association between Customer and
Order, but how should we represent Order /
LineItem / Product? I've chosen to map
LineItem as an association class representing the many-to-many
association between Order and Product. In
Hibernate, this is called a composite element.
The mapping document:
]]>
customers, orders, line_items and
products hold customer, order, order line item and product data
respectively. line_items also acts as an association table linking
orders with products.
Miscellaneous example mappings
These examples are all taken from the Hibernate test suite. You
will find many other useful example mappings there. Look in the
test folder of the Hibernate distribution.
TODO: put words around this stuff
"Typed" one-to-one association
name
'HOME'
name
'MAILING'
]]>
Composite key example
( select sum(li.quantity*p.price)
from LineItem li, Product p
where li.productId = p.productId
and li.customerId = customerId
and li.orderNumber = orderNumber )
( select sum(li.quantity)
from LineItem li
where li.productId = productId )
]]>
Many-to-many with shared composite key attribute
org
org
]]>
Content based discrimination
case
when title is not null then 'E'
when salesperson is not null then 'C'
else 'P'
end
]]>
Associations on alternate keys
]]>