• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

many-to-one delete problem

 
Steven Gollery
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two classes -- call them A and B. On the Java side, A has a reference to B. I map that association in the mapping for A like this:

<many-to-one name="myB" column="myBkey" class="B" cascade="save-update"/>

B has no association with A. B's mapping is:

<hibernate-mapping>
<class name="org.me.B" table="B">
<id name="id" column="b_key" type="long">
<generator class="native" />
</id>
<property name="abbreviation">
<column name="abbrev" unique="true"/>
</property>
<property name="name">
<column name="name" unique="true"/>
</property>
</class>
</hibernate-mapping>


Now I create an instance of A and set its myB field to an instance of B. I persist both objects. So far fine.

Now I want to delete the instance of B, but naturally I get a foreign key constraint violation error.

A couple of things to note here:

1. There are no collections involved.
2. B has no association with A.

These two facts are enough to make all the solutions I've seen inoperable.

Is there some way to set up this mapping so Hibernate will automatically find all the rows in table A whose myBkey column is equal to the b_key of the B that I'm deleting, and set those columns to null? Or do I have to write the code to do it? Or add an association from B to A which does not match the semantics of the underlying domain model?

Any thoughts?
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You object model does not and should not match your data model. Not sure if what you were saying at the end was the opposite of this?

Here's the thing, because you don't have a B to A mapping, and you have only one A for the B, when that B has many A's. How is Hibernate supposed to know all the B's that it would need to delete? So I think a mapping on the B side to the A, you can map this with access="field" so that you don't need to have a getter and setter which will make the application not able to traverse from the B to the A's, and then put a cascade option of "orphan-delete"

Mark
 
Steven Gollery
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark,

Thanks for the reply. I understand what you mean about the object model not necessarily matching the data model. I expected that there wouldn't be a way to accomplish what I wanted to do automatically, but it seemed worth asking about just in case.

Steven Gollery
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic