I used Set to store many-to-one association, but I happened a boring problem. Although it is a j2se Set problem, it occurs in using hibernate.
My business logic is: Add a new detail Item to parent, save it to database. If any dababase exception(HibernateException) orrur, break the association.
So my code is like this:
Code:
Parent class:
void addChild(Child child) throws Exception {
this.children.add(child);
child.setParent(this);
try{
//call a DAO method to store.
}catch(HibernateException){
this.children.remove(child);
child.setParent(null);
}
}
But I found the Set:children would not remove child correctly. I think the reason is diffierent hashCode between child instance adding to Set and child instance removing from set.
Did anyone happen this problem before? Please share your solution?
Again, If I add a batch of children, then store at last. If occur HibernateException, I call method session.refresh to reload correct data from DB. Is it a good solution?