Hi All,
I'm new to Hibernate & am having trouble with deleting an object that is part of a Parent-Child relationship. Yes, I've read the chapters in the documentation. But, obviously, I'm still missing something! :)
I have an object "Group" that can has two types of children: Users and other Groups. (This is kind of like a directory that can have both files & other directories as children.) Adding and updating Groups is not a problem. When I try to delete a Group that is a child of another group, I get a foreign key constraint failure. Which is makes sense. So I modified my code to remove the child from the parent relationship and remove all it's children too. Unfortunately, when I try this, I get the following exception when I try to update the parent : HibernateException: Illegal attempt to associate a collection with two open sessions. I don't understand why this would be happening.
The exception seems to be throw at line 1104 of SessionImpl:
Code:
// a collection loaded in the current session
// can not possibly be the collection belonging
// to the entity passed to update()
removeCollection(persister, id);
My code & mapping xml follow.
Any help would be greatly appreciated!!! :)
Linda:)
The session returned below uses the ThreadLocal pattern described on the Hibernate webiste.
Code:
public void deleteGroup(UserGroup delGroup) throws Exception
{
Session session = null;
Transaction trx = null;
try
{
session = Persistence.instance.getSession();
trx = session.beginTransaction();
java.util.Iterator parents = delGroup.getParents().iterator();
while(parents.hasNext())
{
UserGroup parent = (UserGroup) parents.next();
parent.removeGroup(delGroup);
session.update(parent);
}
delGroup.setUsers(null);
delGroup.setGroups(null);
delGroup.setParents(null);
session.delete(delGroup);
trx.commit();
}
catch (Exception e)
{
trx.rollback();
throw e;
}
finally
{
session.close();
}
}
UserGroup.hmb.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="com.po.review.data.UserGroup"
table="userGroup"
persister="net.sf.hibernate.persister.EntityPersister"
>
<id name="id"
column="id"
type ="long"
unsaved-value="-1">
<generator class="native"/>
</id>
<property name ="name"
column ="name"
type ="string"
length ="25"
not-null ="true"
unique ="true"
/>
<property name ="description"
column ="description"
type ="string"
length ="128"
not-null ="false"
/>
<set name="users"
table="group_user">
<key column="group_id"/>
<many-to-many class="com.po.review.data.User" column="user_id"/>
</set>
<set name="groups"
table="group_subgroup">
<key column="group_id"/>
<many-to-many class="com.po.review.data.UserGroup" column="subGroup_id"/>
</set>
<set name="parents"
inverse="true"
table="group_subgroup">
<key column="subGroup_id"/>
<many-to-many class="com.po.review.data.UserGroup" column="group_id"/>
</set>
</class>
</hibernate-mapping>