How to delete old child records when updating the Parent Entity
I am currently working on a Bi-directional OneToMany Hibernate association using annotations. I am stuck up with a problem.
A Parent entity has many child entities. Whenever I update the Child set in Parent and try to update the Parent entity, still the old Child entries exists in the Child table. so Parent contains duplicate child records.
Whenever I update Parent entity, automatically its Child entries should also be updated correctly with no duplicates, meaning already existing child entities should be deleted.
I googled and found that there is a dirty way of achieving this. Getting the existing Child entitie开发者_运维百科s of a Parent and iterating through each child and deleting each child entity using session.delete(child). This is very bad approach, I know.
Can we achieve the above thing in a better way using annotations? Please help me in resolving this.
Use the delete-orphan cascade setting. When a child is removed from the parent, the child will be deleted.
You will have to modify the collection that was loaded and exists in the session for delete-orphan to work. Which means the collection has to be a PersistentSet or whatever and you remove and add objects to it.
Something like
Set<Product> newProducts = new HashSet<Products>();
newProducts.add(prod1);
newProducts.add(prod2);
order.setProducts(newProducts);
will only set the parent_id int he products table to null, it won't delete them. Now something like
Set<Product> products = order.getProducts();
products.clear();
products.add(prod1);
products.add(prod2);
should delete the children.
And remember for any delete-orphan to work the orders and products must be loaded and exist in the session.
精彩评论