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

后端 未结 18 1139
轮回少年
轮回少年 2020-11-30 00:19

i have the following two entities:

1- PlayList:

@OneToMany(fetch = FetchType.EAGER, mappedBy = \"playlist\", orphanRemoval = true, c         


        
相关标签:
18条回答
  • 2020-11-30 00:53

    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);
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-30 00:55

    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 :)

    0 讨论(0)
  • 2020-11-30 00:57

    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.

    0 讨论(0)
  • 2020-11-30 01:00

    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);
    
    0 讨论(0)
  • 2020-11-30 01:00

    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.

    0 讨论(0)
  • 2020-11-30 01:00

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

    0 讨论(0)
提交回复
热议问题