Hi,
I've got a question that's a little long-winded to ask, so please bear with me. I was wondering how to manage a many-to-many relationship with a mapping similar to this:
<class name="Document" table="document">
...
<list name="subjects" table="document_to_subject">
<key column="document_id" />
<list-index column="index" />
<many-to-many class="Subject" column="subject_id" />
</class>
<class name="Subject" table="subject">
...
</class>
A document can have many subjects, and a subject can belong to many documents. If I delete a document, and all of its subjects belonged to other documents, that's no problem. If I delete a document, and one of its subjects doesn't belong to any other document, I end up with an orphan.
//Document doc1 has subjects subj1 and subj2
//Document doc2 has subject subj1
...
doc1.removeSubject(subj1);
//This is no problem, the result is just one row for doc1 in the document_to_subject table
session.saveOrUpdate(doc1);
...
//Here's where subj2 gets orphaned
session.delete(doc1);
Once doc1 is deleted, there will still be a row for subj2 hanging around in the subject table. The behaviour I'm looking for is that orphaned Subjects will be discarded when there are no Documents that reference them.
My question is: can Hibernate fix this automatically (maybe by making the association bi-directional?), or do I have to explicitly check for orphaned subjects each time I delete a document?
|