Let's say I have a many-to-many from one entity A to another entity B. And let's say that there could be many, many, many B's associated with a given instance a1.
Now I want to delete a1. In order for this to work, I need to clean up the A-to-B association. Here's some code that could do it:
Code:
Iterator bInstances = a1.getBSet().iterator();
while (bInstances.hasNext()) {
a1.getBSet().remove(bInstances.next());
}
But this doesn't work because this leads to ConcurrentModificationExceptions. So let's try this:
Code:
Set bSet = new HashSet(a1.getBSet());
Iterator bInstances = bSet.iterator();
while (bInstances.hasNext()) {
a1.getBSet().remove(bInstances.next());
}
No more ConcurrentModificationExceptions because we're now iterating a different set than we're removing from. But now we have an efficiency problem! The bSet has to be completely populated, which could be a very large load, simply in order to turn around and delete it all. Not to mention that both of these alternatives involve one database round trip per A-to-B reference.
What I really want is a way to tell Hibernate to do the equivalent of "delete from a_to_b where a_to_b.a_id = <a1.getId()>" in one shot, so I can wipe the whole collection table in one database hit.
Is there any way to do this?
Cheers!
Rob