I have two classes which have a many to many bi-directional relationship with each other.
Code:
<class name="Pattern" table="PATTERN">
<id name="id" column="id" type="long" unsaved-value="null">
<generator class="native"/>
</id>
<property name="name" column="name" type="string" not-null="true" length="100"/>
<!-- many to many bi-directional with Style -->
<set name="styles" table="STYLE_PATTERN_JT">
<key column="pattern_id"/>
<many-to-many column="style_id" class="Style"/>
</set>
</class>
<class name="Style" table="STYLE">
<id name="id" column="id" type="long" unsaved-value="null">
<generator class="native"/>
</id>
<property name="name" unique="true" column="name" type="string" not-null="true" length="100"/>
<!-- many to many bi-directional with Pattern -->
<set name="patterns" table="STYLE_PATTERN_JT" inverse="true">
<key column="style_id"/>
<many-to-many column="pattern_id" class="Pattern"/>
</set>
</class>
I create two Patterns and two Styles:
PatternA
PatternB
StyleA
StyleB
I then associate both patterns with both styles, so I have the following associations in the join table:
Code:
mysql> select pattern_id, style_id from style_pattern_jt;
+------------+----------+
| pattern_id | style_id |
+------------+----------+
| 1 | 1 |
| 2 | 1 |
| 1 | 2 |
| 2 | 2 |
+------------+----------+
If I then (using Hibernate Session) delete the pattern with an id of 1, The pattern is deleted from the pattern table and I am left with the following in the join table:
Code:
mysql> select pattern_id, style_id from style_pattern_jt;
+------------+----------+
| pattern_id | style_id |
+------------+----------+
| 2 | 1 |
| 2 | 2 |
+------------+----------+
Which seems correct to me.
However, if I create the associations as above, but delete a style instead, for example deleting style with id number 1, the style is deleted as expected, but there are still four association rows in the join table:
Code:
mysql> select pattern_id, style_id from style_pattern_jt;
+------------+----------+
| pattern_id | style_id |
+------------+----------+
| 1 | 1 |
| 2 | 1 |
| 1 | 2 |
| 2 | 2 |
+------------+----------+
The first two rows are now 'orphans' as there is no longer a style with id of 1. This does not seem correct to me.
I have tried moving the inverse="true" to the other end of the association in the mapping file and I get the opposite results, in other words, deleting style now works and deleting pattern does not.
I have tried using cascade="delete", but this does not solve the 'orphan' problem
Don't get me wrong, Hibernate still navigates my associations correctly, i.e. it ignores the first two rows in the join table, but I am concerned that it is not good housekeeping to have obsolete rows in my join table
could someone have a look at my mapping files and let me know if I have made a mistake, or if it is expected behaviour,
many thanks
Daniel
ps I am using MySQL 3.23.39 Hibernate 2.1.1