We have a bidirectional many-to-many mapping with a list on one side and a set on the inverse side. I found that if I remove the first item from the list, the primary key uniqueness constraint is violated.
Unfortunately, I don't have a debug log with me here (I'm at home right now). I'll give pseudocode for the SQL that was generated, because this will better illustrate what the problem is anyhow:
Imagine that the join table has three columns: Table1Key_ID, Table1Key_Index and Table2Key_ID. My list has three items, the first of which is being deleted. Here's a sample table:
Code:
Table1Key_ID Table1Key_Index Table2Key_ID
44 0 55
44 1 66
44 2 77
1) delete from JoinTable where Table1Key_ID = 44 and Table2Key_ID = 77
2) update JoinTable set Table2Key_ID=66 where Table1Key_ID=44 and Table1Key_Index=0
3) update JoinTable set Table2Key_ID=77 where Table1Key_ID=44 and Table1Key_Index=1
That second query fails, because the primary key on the join table is Table1Key_ID, Table2Key_ID, and the 44-66 pair already exists at index 1.
We *could* make the primary key use all three columns and this problem would go away. But, that's not really the relationship we want to model, because a pair should not appear in here more than once.
We could also replace the collection with a new collection, which would cause Hibernate to delete all of the rows and re-add them. That's not ideal, either, obviously...
Is there some other way to avoid violating this constraint?
Thanks in advance...
Kevin
Here is the mapping:
<list
name="appearsOnPage"
table="Article_AppearsOnPage_Page"
lazy="true"
inverse="false"
cascade="none"
>
<key
column="Article_AppearsOnPage_ID"
/>
<index
column="AppearsOnPage_Index"
/>
<many-to-many
class="org.jstor.model.repository.Page"
column="Page_ID"
outer-join="auto"
/>
</list>
and from the inverse side:
<set
name="articlesOnPage"
table="Article_AppearsOnPage_Page"
lazy="true"
inverse="true"
cascade="none"
sort="unsorted"
>
<key
column="Page_ID"
/>
<many-to-many
class="org.jstor.model.repository.Article"
column="Article_AppearsOnPage_ID"
outer-join="auto"
/>
</set>
Hibernate 2.1.2, MySQL 4 w/INNO DB.[/code]