File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes Preventing duplicates on a many to many relationhship Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Preventing duplicates on a many to many relationhship" Watch "Preventing duplicates on a many to many relationhship" New topic

Preventing duplicates on a many to many relationhship

Sonx Nkuks
Ranch Hand

Joined: Aug 20, 2010
Posts: 47
Hi .. say i have three tables Override (Parent), OverrideItems (Link Table), Items (Child). Item has only two columns "ItemID" (primary key) and "ItemValue". When i add new Override and its items i would like to reuse existing ItemValue if user has entered existing ItemValue for the new Override. Otherwise inserts new ItemValue if none existing. I noticed a "many-to-many" unidirectional mapping will allow duplications meaning i could have same item inserted with different ItemID, how do i avoid this? Is making ItemValue UNIQUE Index/Constraint enough to enforce this
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

So basically you don't want duplicate ItemValue's. Then yes making it unique is enough.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Abhishek Ralhan
Ranch Hand

Joined: Aug 01, 2010
Posts: 40

You may be already aware, but incase you are not, unique constraint allows one null value. So you may have to handle it through code.

I came to this world on a Learner's License
Waswani Naresh
Ranch Hand

Joined: May 01, 2008
Posts: 66
Hi Sonx,

In your case, I guess you don't have item id's while saving Override instance because of which Hibernate would always try to insert new record for item instances. If you could manage to get items id's before saving then Hibernate would not insert new item record if it already exists.

In general, when you use many-to-many mapping, you have the IDs with you and that's how you implement many-to-many properly.

Naresh Waswani

Naresh Waswani
Madhan Sundararajan Devaki
Ranch Hand

Joined: Mar 18, 2011
Posts: 312

You may make ItemValue a Primary Key.

Not many get the right opportunity !
I agree. Here's the link:
subject: Preventing duplicates on a many to many relationhship
jQuery in Action, 3rd edition