2

I'm inherited a hibernate mapping and am having trouble moving a child node from one parent node to another. Either I get a duplicate reference, or I get an error.

I have locations in a tree. I want to move one leaf node to another leaf position. In code I'm trying to do this:

GeographicLocation oldParent = location.getParent();
location.setParent(newParent);
newParent.getChildren().add(location);
oldParent.getChildren().remove(location);

Causes:

org.hibernate.ObjectDeletedException: deleted object would be re-saved by cascade (remove deleted object from associations): [com.test.GeographicLocation#11]

If I remove the line oldParent.getChildren().remove(location), the newParent node correctly points to the child, but the oldParent still has a reference to the child as well(!).

Snippets from hibernate config file:

<class name="GeographicLocation" table="GeographicLocation">
  <id column="GeographicLocationId" name="geographicLocationId" type="java.lang.Long">
    <generator class="native">
      <param name="sequence">GeographicLocationId</param>
    </generator>
  </id>

<many-to-one class="com.test.GeographicLocation"
   foreign-key="ParentFK" name="parent">
  <column name="parent"/>
</many-to-one>

<bag cascade="all,delete-orphan" inverse="true" lazy="false" name="children">
  <key column="parent" not-null="true"/>
  <one-to-many class="com.test.GeographicLocation"/>
</bag>

I haven't been using Hibernate very long. My understanding is that the location node, being a managed object, will save itself when modified. Since the hibernate config file specifies cascade=all changes to the collection will also save changes to the child. However, I can't seem to find a legal way to remove the old reference. Any help?

Matt Thompson
  • 773
  • 1
  • 10
  • 26
  • Seems a duplicate of:http://stackoverflow.com/questions/11649249/deleted-object-would-be-re-saved-by-cascade-remove-deleted-object-from-associat – dan Oct 09 '12 at 20:11

1 Answers1

1

I would remove the delete-orphan from the mapping, since it says that as soon as you remove an element from the collection, it should be removed (which is clearly not what you want).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255