Thursday, June 5, 2008

Delete procedure of One to One relationship in Hibernate

I found out that Cascading does not work for 1-to1 relationship. We have to cater for it specifically.

The story is, i mapped 2 entities with each of them having a "many-to-one" relationship to represent a 1-to-1 relationship. I did not use the "1-to-1" mapping because it caused some problems which i now can not remember anymore.

Let's call the 2 entities as "parent" and "friend". 1 parent has 1 friend.

Now, I want to just delete "parent" and hope that its children will get deleted automatically.


  1. Therefore i will do a "session.delete(parent)". However this will throw an exception saying that "parent" is referencing another entity "friend".

  2. So, I will now get the "friend" from "parent" first by doing "Friend friend = parent.getFriend()".

  3. Then, i do a "parent.setFriend(null)" and saved the parent by doing "session.save(parent)". The "parent-friend" 1-to-1 relationship is being removed now.

  4. Next i delete the friend by doing "session.delete(friend)".

  5. Lastly, i will do a "session.delete(parent)". The parent will now be removed together with its children!

No comments:

Post a Comment