jump to navigation

Capturing n-to-n relationships, Hibernate etc. September 18, 2006

Posted by javafoo in ER - Entity Relationship, hibernate, javanotes, OOAD.

So I was trying to capture a one-to-one relationship in Hibernate. I really started thinking about n-to-n relationships and how you can get confused as to where the foreign key goes. I came up with this thumb rule if you have a one-to-many or a many-to-one realtionship the foreign key column id always goes into the “many” end. For ex: I have a one-to-many relationship between Order and OrderLineItem. Since the OrderLineItem is the many end, it will end up holding the Order_id field. So what happens when there is a many-to-many relationship, in that case you have a link table which will hold the primary key ids of both the objects as foreign keys.

Going back to the one-to-one problem, the hibernate config task was not adding the foreign key id, so as a work around I changed it to many-to-one. When I found that it was already mentioned on the hibernate site:

There are two varieties of one-to-one association:

  • primary key associations
  • unique foreign key associations

So I had effectively done option 2.

Also when creating one-to-many relationships there is a caveat. I was running into constraint violations and found this on the hibernate site: “If the <key> column of a <one-to-many> association is declared NOT NULL, Hibernate may cause constraint violations when it creates or updates the association. To prevent this problem, you must use a bidirectional association with the many valued end (the set or bag) marked as inverse="true".” or do away with all foreign key constraints, I opted for the second option.

If only we spend more time on reading documentation. But there’s no better way than learning from mistakes and then struggling to solve them and finally solving them and then realizing that it was already documented. 😉



No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: