15

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.

user2323036
  • 1,515
  • 5
  • 19
  • 27

4 Answers4

22

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

Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69
  • 1
    hibernate users should use this for orphan removal @Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) – Akhilesh Nov 16 '13 at 19:08
6

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.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
3

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
Ankit Katiyar
  • 2,631
  • 2
  • 20
  • 30
1

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.

Navin Israni
  • 1,327
  • 3
  • 15
  • 27