0

I understand that this is a reasonably common problem with Hibernate, however I am still struggling to write code that functions correctly. Basically, I have two classes; Demographic and NextOfKin. The later is related to Demographic as a One-To-Many Set. Simplified:

<hibernate-mapping>
          <class name="entities.Demographic" table="Demographics">

            <id name="id" type="long" column="Id" ><generator class="identity"/></id>
            <set name="nextOfKinList" table="NextOfKin" inverse="true" lazy="true" fetch="select" cascade="all,delete-orphan" >
                <key><column name="DemographicId" not-null="true" /></key>
                <one-to-many class="entities.NextOfKin" />
            </set>
         </class>
</hibernate-mapping>


<hibernate-mapping>
        <class name="entities.NextOfKin" table="NextOfKin">
            <id name="id" type="long" column="Id" ><generator class="identity"/></id>  
            <many-to-one name="demographic" class="entities.Demographic" fetch="select">
                <column name="DemographicId" not-null="true" />
            </many-to-one>
</hibernate-mapping>

The code I am trying to use remove the list of NextOfKin follows - again simplified:

    try {
        DAOFactory factory = DAOFactory.instance(DAOFactory.HIBERNATE);
        HibernateUtil.beginTransaction();
        Demographic demographic = factory.getDemographicDAO().findDemographic();        

        if (!demographic.getNextOfKinList().isEmpty()) {
            for (Iterator<NextOfKin> iterator = demographic.getNextOfKinList().iterator(); iterator.hasNext();) {
                NextOfKin nextOfKin = iterator.next();
                factory.getNextOfKinDAO().delete(nextOfKin);
                iterator.remove();
            }
        }
        demographic.setNextOfKinList(nextOfKinList);
        HibernateUtil.commitTransaction();
    }
    catch (Exception e) {
        e.printStackTrace();
        HibernateUtil.rollbackTransaction();
    }
    finally {
        HibernateUtil.closeSession();
    }

I have tried several approaches, but all have failed either leaving the relationship intact or as with the current example throwing an Exception:

org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: entities.Demographic.nextOfKinList

Apologies as this is a fairly standard question, but any assistance would be appreciated.

4

2 回答 2

3

你只需要清除集合:demographic.getNextOfKinList().clear()。Hibernate 会自动从数据库中删除元素,这就是delete-orphan.

if (!demographic.getNextOfKinList().isEmpty()) {
     demographic.getNextOfKinList().clear();      
}

并删除该行:demographic.setNextOfKinList(nextOfKinList);如果要向集合中添加新元素,请将它们添加到现有集合中:

demographic.getNextOfKinList().add(newElem)

于 2013-05-09T04:56:36.003 回答
1

与其一一删除,不如试试这个。

demographic.getNextOfKinList().clear();

demographic.getNextOfKinList().addAll(nextOfKinList);
于 2013-05-09T04:54:33.330 回答