简体   繁体   中英

A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance how to deal with it?

What possibly could be a problem with this?

Caused by: org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: com.en.test.father.Father.listSons
    at org.hibernate.engine.internal.Collections.processDereferencedCollection(Collections.java:99)
    at org.hibernate.engine.internal.Collections.processUnreachableCollection(Collections.java:50)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushCollections(AbstractFlushingEventListener.java:243)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:86)
    at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:44)
    at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1251)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1962)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)

My getter and setter method

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    @JoinColumn(name = "FATHERID", nullable = false)
    @OrderBy("id ASC")
    public List<Sons> getListSons() {
        return listSons;
    }

    public void setListSons(List<Sons> listSons) {
            this.listSons.clear();
            this.listSons.addAll(listSons);
    }

I supposed that list should be not initialize but clear and then added element, but even this i got this errors

You have not show your domain model but probably old list of sons still reference Father entity. Set father field to null for each Son object. It would look something like this:

    public void setListSons(List<Sons> listSons) {
            this.listSons.stream().forEach(oldSon -> oldSon.setFather(null));
            this.listSons.clear();
            this.listSons.addAll(listSons);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM