deleted object would be re-saved by cascade (remove deleted object from associations)

The solution is to do exactly what the exception message tells you:

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

Remove the deleted object from an associations (sets, lists, or maps) that it is in. In particular, i suspect, from PlayList.PlaylistadMaps. It's not enough to just delete the object, you have to remove it from any cascading collections which refer to it.

In fact, since your collection has orphanRemoval = true, you don't need to delete it explicitly. You just need to remove it from the set.

problem solved after changing the FetchType to Lazy

Dmitry Ginzburg

If you don't know, which collection holds your object

In my case it was really hard to apply TomAnderson's solution, since I didn't know what is the collection, which holds a link to an object, so here's the way to know, which objects holds the link to the deleted one: in the debugger you should enter the lowest execution stack level before the exception is thrown, there should be a variable called entityEntry, so you get a PersistenceContext object from this variable: entityEntry.persistenceContext.

For me persistenceContext was an instance of StatefulPersistenceContext and this implementation has private field parentsByChild, from which you can retrieve information about the collection, which contains the element.

I was using Eclipse debugger, so it was kinda hard to retrieve this private field in a straight way, so I used Detail Formatter (How can I watch private fields of other objects directly in the IDE when debugging?)

After getting this information, TomAnderson's solution can be applied.

I was able to resolve this by writing the code below. I used executeUpdate instead of .delete()

def publicSupport = caseObj?.client?.publicSupport
        if(publicSupport)
            PublicSupport.executeUpdate("delete PublicSupport c where c.id = :publicSupportId", [publicSupportId:publicSupport.id])
            //publicSupport.delete()

Some how all the above solutions did not worked in hibernate 5.2.10.Final.

But setting the map to null as below worked for me:

playlist.setPlaylistadMaps(null);
Jake

I encountered this exception message as well. For me the problem was different. I wanted to delete a parent.

In one transaction:

  • First I called up the parent from the database.
  • Then I called a child element from a collection in the parent.
  • Then I referenced one field in the child (id)
  • Then I deleted the parent.
  • Then I called commit.
  • I got the "deleted object would be resaved" error.

It turns out that I had to do two separate transactions. I committed after referencing the field in the child. Then started a new commit for the delete.

There was no need to delete the child elements or empty the collections in the parent (assuming orphanRemoval = true.). In fact, this didn't work.

In sum, this error appears if you have a reference to a field in a child object when that object is being deleted.

Kind of Inception going on here.

for (PlaylistadMap playlistadMap : playlistadMaps) {
        PlayList innerPlayList = playlistadMap.getPlayList();
        for (Iterator<PlaylistadMap> iterator = innerPlayList.getPlaylistadMaps().iterator(); iterator.hasNext();) {
            PlaylistadMap innerPlaylistadMap = iterator.next();
            if (innerPlaylistadMap.equals(PlaylistadMap)) {
                iterator.remove();
                session.delete(innerPlaylistadMap);
            }
        }
    }

Another workaround

I completely agree with redochka and Nikos Paraskevopoulos. Mahmoud Saleh's answer get over the issue in some circumstances not every time. In my situation I really need Eager fetchtype. So as Stony mentioned above I just removed from a list which cantian the object too. Here is my code:

Rju entity

public class Rju extends AbstractCompany implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 4294142403795421252L;


    //this field just duplicates @Column(name="callname") and serves for mapping to Rju fullname field
    @Column(name = "fullname")
    private String namerju;
    @NotEmpty
    @Column(name = "briefname")
    private String briefname;

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "otd")
    private Collection<Vstan> vStanCollection;

//  @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "rju", orphanRemoval = true)
    private Collection<Underrju> underRjuCollection;
.........
}

Underrju entity

public class Underrju extends AbstractCompany implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 2026147847398903848L;


    @Column(name = "name")
    private String name;

    @NotNull
    @Valid
    @JoinColumn(name = "id_rju", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Rju rju;
......getters and setters..........
}

and my UnderrjuService

@Service("underrjuService")
@Transactional
public class UnderRjuServiceImpl implements UnderRjuService {

    @Autowired
    private UnderRjuDao underrjuDao;

    .............another methods........................
    @Override
    public void deleteUnderrjuById(int id) {
        Underrju underrju=underrjuDao.findById(id);
        Collection<Underrju> underrjulist=underrju.getRju().getUnderRjuCollection();
        if(underrjulist.contains(underrju)) {
            underrjulist.remove(underrju);
        }
        underrjuDao.delete(id);

    }
     .........................
}

Because i need FetchType to be EAGER, i remove all associations by setting them to (null) and save the object (that remove all association in the database) then delete it!

That add some milliseconds but it's fine for me, if there better way to keep those MS add your comment bellow..

Hope that help someone :)

I also ran into this error on a badly designed database, where there was a Person table with a one2many relationship with a Code table and an Organization table with a one2many relationship with the same Code table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.

What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.

Morten Holmgaard

This post contains a brilliant trick to detect where the cascade problem is:
Try to replace on Cascade at the time with Cascade.None() until you do not get the error and then you have detected the cascade causing the problem.

Then solve the problem either by changing the original cascade to something else or using Tom Anderson answer.

I had the same exception, caused when attempting to remove the kid from the person (Person - OneToMany - Kid). On Person side annotation:

@OneToMany(fetch = FetchType.EAGER, orphanRemoval = true, ... cascade    = CascadeType.ALL)
public Set<Kid> getKids() {    return kids; }

On Kid side annotation:

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "person_id")
public Person getPerson() {        return person;    }

So solution was to remove cascade = CascadeType.ALL, just simple: @ManyToOne on the Kid class and it started to work as expected.

Jai

I was having same issue. I was trying to delete and insert in the same transaction. I added theEntityManager.flush(); after theEntityManager.remove(entity);.

Had the same error. Removing the object from the model did the trick.

Code which shows the mistake:

void update() {
    VBox vBox = mHboxEventSelection.getVboxSelectionRows();

    Session session = HibernateUtilEventsCreate.getSessionFactory().openSession();
    session.beginTransaction();

    HashMap<String, EventLink> existingEventLinks = new HashMap<>();
    for (EventLink eventLink : mEventProperty.getEventLinks()) {
        existingEventLinks.put(eventLink.getEvent().getName(), eventLink);
    }

    mEventProperty.setName(getName());

    for (Node node : vBox.getChildren()) {

        if (node instanceof HBox) {
            JFXComboBox<EventEntity> comboBoxEvents = (JFXComboBox<EventEntity>) ((HBox) node).getChildren().get(0);
            if (comboBoxEvents.getSelectionModel().getSelectedIndex() == -1) {
                Log.w(TAG, "update: Invalid eventEntity collection");
            }

            EventEntity eventEntity = comboBoxEvents.getSelectionModel().getSelectedItem();
            Log.v(TAG, "update(" + mCostType + "): event-id=" + eventEntity.getId() + " - " + eventEntity.getName());

            String split = ((JFXTextField) (((HBox) node).getChildren().get(1))).getText();
            if (split.isEmpty()) {
                split = "0";
            }
            if (existingEventLinks.containsKey(eventEntity.getName())) {
                // event-link did exist
                EventLink eventLink = existingEventLinks.get(eventEntity.getName());
                eventLink.setSplit(Integer.parseInt(split));
                session.update(eventLink);
                existingEventLinks.remove(eventEntity.getName(), eventLink);
            } else {
                // event-link is a new one, so create!
                EventLink link1 = new EventLink();

                link1.setProperty(mEventProperty);
                link1.setEvent(eventEntity);
                link1.setCreationTime(new Date(System.currentTimeMillis()));
                link1.setSplit(Integer.parseInt(split));

                eventEntity.getEventLinks().add(link1);
                session.saveOrUpdate(eventEntity);
            }

        }
    }

    for (Map.Entry<String, EventLink> entry : existingEventLinks.entrySet()) {
        Log.i(TAG, "update: will delete link=" + entry.getKey());
        EventLink val = entry.getValue();
        mEventProperty.getEventLinks().remove(val); // <- remove from model
        session.delete(val);
    }

    session.saveOrUpdate(mEventProperty);

    session.getTransaction().commit();
    session.close();
}

This problem will happen if you delete using PlaylistadMap modal instead of PlayList. in this case FetchType = Lazy is not the right option. It will not throw any exception but only data from PlaylistadMap will get deleted, the data in PlayList will remain in the table. check that also.

chris77
cascade = { CascadeType.ALL }, fetch = FetchType.LAZY