user2323036
user2323036

Reputation: 1585

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

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.

Upvotes: 15

Views: 41119

Answers (4)

Navin Israni
Navin Israni

Reputation: 1377

If you are doing this via XML (and not annotations), below is a solution which worked for me:

One-to-Many Associations:

  1. Remove any link of the child object from any collections in the parent object [NOTE: If you are doing One-to-One association, just set the child object reference in the parent object to "null"]
  2. Delete the child object from the database
  3. flush the changes using session.flush()
  4. Link the parent object to the new child object
  5. Save the parent object 6) commit the changes

CAUTION: session.flush() is important as the Hibernate needs to see the changes,

If you cannot flush the session, I would advise you to do steps (1,2) in a different transaction and then do steps (4,5,6) in a new transaction.

Upvotes: 1

Ankit Katiyar
Ankit Katiyar

Reputation: 3001

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

Upvotes: 3

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18423

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

Upvotes: 23

Jens Schauder
Jens Schauder

Reputation: 81998

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.

Upvotes: 6

Related Questions