Hi all,
I have a parent/child relationship and when the parent is deleted, i need to remove the references to the parent from all of it's children and keep them and then delete the parent. I'd like this to happen in one transaction so that if the final delete fails, the references are kept. I'm having trouble, hibernate is complaining that the parent is already referenced in the session. I'm assuming this is because it's attached to the session when i use it as a parameter for the children query, or when the children return with references to the parent. I've tried using evict and merge methods.
any tips appreciated.
Thx, paul.
Hibernate version: 3.2.3ga
Mapping documents:
Code:
<hibernate-mapping>
<class name="com.Parent">
<id name="id" column="pk"><generator class="native"/></id>
</class>
</hibernate-mapping>
Code:
<hibernate-mapping>
<class name="com.Child">
<id name="id" column="pk"><generator class="native"/></id>
<many-to-one name="parent" class="com.Parent" lazy="false"/>
</class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():Code:
// Parent parent (argument)
Session session = sFac.getSession();
try
{
session.beginTransaction();
Query qry = session.createQuery("FROM " + Child.class.getName() + " AS child WHERE child.parent=:parent");
qry.setEntity("parent", parent);
for (Child child : (List<Child>) qry.list())
{
child.setParent(null);
session.saveOrUpdate(child);
}
session.delete(parent); // <-- exception thrown here
session.getTransaction().commit();
}
catch (RuntimeException e)
{
rollback();
throw e;
}
Full stack trace of any exception that occurs:Code:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.Parent#30]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:578)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:99)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:52)
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:766)
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:744)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:301)
at $Proxy13.delete(Unknown Source)
Name and version of the database you are using: HSQLDB