Next Previous Index

15. Ternary Associations (and beyond)


Definition:

Ternary associations are those that involve three first-rank classes. First-rank classes A, B and C are associated together in a relationship.


Scenario:

We have first-rank classes Foo, Bar and Snafu which are all related together. We choose to store their relationship in Foo using a composite class BarSnafu:


Bar   BarSnafu.getBar()    // Retrieve Bar from BarSnafu
Snafu BarSnafu.getSnafu()  // Retrieve Snafu from BarSnafu
Set   Foo.getBarSnafus()   // Retrieve set of BarSnafus from Foo

Hibernate Mapping:

In Hibernate, this could be mapped as follows:


<class name="Foo" table="foo">
    ...
    <set role="barsnafus" table="foo_bar_snafu">
        <key column="foo_id"/>
        <composite-element class="BarSnafu">
            <many-to-one name="bar" class="Bar" column="bar_id"/>
            <many-to-one name="snafu" class="Snafu" column="snafu_id"/>
        </composite-element>
    </set>
</class>
...

Table Schema:

Foo

id

Bar

id

Snafu

id

Foo_Bar_Snafu

foo_id

bar_id

snafu_id


So here we've got three first-rank classes. They are related together in table foo_bar_snafu. The result is stored as a set of BarSnafu instances on each Foo. Each BarSnafu instance references one Bar and one Snafu.


Simple huh?


NB: Using composite elements we can go beyond this and support 4 and more elements in a relationship.


Bidirectionality:

Bidirectionality has no meaning for a ternary relationship.



Next Previous Index