Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Preventing duplicates on a many to many relationhship

 
Sonx Nkuks
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So basically you don't want duplicate ItemValue's. Then yes making it unique is enough.
 
Abhishek Ralhan
Ranch Hand
Posts: 40
Chrome Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Waswani Naresh
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


Regards,
Naresh Waswani
 
Madhan Sundararajan Devaki
Ranch Hand
Posts: 312
Java MS IE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may make ItemValue a Primary Key.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic