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.