Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations):

Tags:

hibernate

i am getting the above error "org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): ". could someone help me what might be the issue and what should be the fix?

Thanks.

like image 763
user2323036 Avatar asked Aug 21 '13 13:08

user2323036


3 Answers

Without mapping end code is a bit hard... This is caused, usually, because you are deleting an object associate to a collection.
You have to remove object from owning collection(s) and, after, delete object

parentObject.collection.remove(objToDelete);
session.delete(objToDelete);
session.save(parentObject);

But you can avoid this using deleteOrphan to mapped collection in this way

class ParentObject {
  @OneToMany(orphanRemoval=true)
  private List<ChildObject> collection;
}

and code looks like

parentObject.collection.remove(objToDelete);
session.save(parentObject);

You don't more need object deletion because it is automatically removed by Hibernate when saving parentObject.

Hope can help

like image 159
Luca Basso Ricci Avatar answered Nov 13 '22 10:11

Luca Basso Ricci


You have deleted an entity (A) in the session, but it is referenced by another entity and is anotated with a Cascade annotation. That reference would cause the entity (A) to be reacreated immediatly. Since this is probably not what you intended, hibernate complains.

The solution is to find all references (including collections) via which the entity is reachable and set them to null/remove the entity from the collection.

You can turn your delete logic around: make the reference (if there is only one) a delete orphan and just remove it there as @bellabax described.

like image 6
Jens Schauder Avatar answered Nov 13 '22 11:11

Jens Schauder


This exception tells that Object that you are deleting is also mapped with collection of any entity, and your cascade in that collection id all. So if you want to delete any way you can change your cascade to

cascade = CascadeType.DETACH
like image 3
Ankit Katiyar Avatar answered Nov 13 '22 12:11

Ankit Katiyar