Hello, I have a class with a bidirectionnal relation to itself : a category can be have several child and have one parent.
Everything is fine except when I try to change the parentcategory. The category is "moved" to the new one but is not deleted from on the old one.
So I get two duplicated categories...
What's wrong ?
Thank you
Hibernate version: 3.0.5
Mapping documents:
Code:
<class name="Category" table="category">
<id name="id" type="long" column="id">
<generator class="native"/>
</id>
<!-- Properties -->
<property name="title" column="title" type="string" length="64" not-null="true"/>
<!-- owns Several child categories -->
<set name="childCategories" cascade="all-delete-orphan" inverse="true" lazy="true">
<key column="parent_category_id"/>
<one-to-many class="Category"/>
</set>
<!-- And optionnaly a parent (can be a root also) -->
<many-to-one name="parentCategory" cascade="none" outer-join="false"
class="Category">
<column name="parent_category_id" not-null="false"/>
</many-to-one>
<!-- Contains messages -->
<set name="messages" inverse="true" lazy="true" cascade="all-delete-orphan">
<key column="categoryid"/>
<one-to-many class="Message"/>
</set>
</class>
Code between sessionFactory.openSession() and session.close():Code:
Category parentCategory = category.getParentCategory();
if(parentCategory != null)
parentCategory = categoryDAO.getCategory(parentCategory.getId()); // reload parent
if(category.getId() == null) // New category
/* skip */
else
{
saveCategory = categoryDAO.getCategory(category.getId()); // get cat from DB
// Is there a parent ? Has the parent changed ?
if(parentCategory != null && category.getParentCategory().getId() != saveCategory.getParentCategory().getId())
{
saveCategory.getParentCategory().getChildCategories().remove(saveCategory);
parentCategory.getChildCategories().add(saveCategory);
}
shallowCopy(category,saveCategory); // Just simple properties are copied here
}
categoryDAO.makePersistent(saveCategory);