Hi everyone.
In my application, many relationships are modeled as many-to-one and many-to-many. The problem I am facing right now is deleting the orphans.
Assume we have m:m A:B and m:1 C:B.
What I want is that when I delete A, all orphan Bs (which are referenced neither from As nor from Cs) are deleted as well. Otherwise I'll get a whole lot of unused Bs in the database.
I don't think Hibernate can do it out of the box.
It requires testing all potential references to B.
I currently have to ideas for a solution.
The first is a dirty trick that we can actually try deleting B and if we get an constraint violation exception, just ignore it (oops, someone references the object) and don't do further cascades.
The second idea is to analyze hibernate mapping metadata to detect all possible references for each of the mapped classes. Then, implement a time-scheduled task which first detects all unreferenced objects and then removes them. In my case, I can just let the database cleared once a day.
Do you see any other options?
|