views:

37

answers:

1

I have a ternary association table created using the following mapping:

<map name="Associations" table="FooToBar">
    <key column="Foo_id"/>
    <index-many-to-many class="Bar" column="Bar_id"/>
    <element column="AssociationValue" />
</map>

I have 3 tables, Foo, Bar, and FooToBar.

When I delete a row from the Foo table, the associated row (or rows) in FooToBar is automatically deleted. This is good.

When I delete a row from the Bar table, the associated row (or rows) in FooToBar remain, with a stale reference to a Bar id that no longer exists. This is bad.

How can I modify my hbm.xml to remove stale FooToBar rows when deleting from the Bar table?

A: 

I haven't tested this... but you could get away by mapping FooToBar in Bar too, like this:

<map name="Associations" table="FooToBar">
    <key column="Bar_id"/>
    <index-many-to-many class="Foo" column="Foo_id"/>
    <element column="AssociationValue" />
</map>

Keep in mind NH does NOT know that foo1[bar1] and bar1[foo1] represent the same row, so be careful with the in-memory state (that is, don't access the elements from both sides in the same session)

Diego Mijelshon