wood burning stoves 2.0*
The moose likes Object Relational Mapping and the fly likes Adding/deleting rows in many-to-many relationship Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Adding/deleting rows in many-to-many relationship" Watch "Adding/deleting rows in many-to-many relationship" New topic
Author

Adding/deleting rows in many-to-many relationship

Eric Jones
Greenhorn

Joined: Mar 19, 2011
Posts: 9
I'm having trouble figuring out how to add and delete rows from the "middle" entity of a many-to-many relationship. I'm using NetBeans IDE.

As a simplified example, I have an entity, "Customer", and this can reference many entities of type "Product". There is a middle entity "Customer_Product" which references a PK entity "Customer_ProductPK".

For a certain Customer, I need to first remove all of the entities in its Customer_ProductList and then replace them with a newly created set.

I've been working with the following basic approach

1) Open a transaction

2) Loop thru the entities in Customer.Customer_ProductList. For each one, I call EntMgr.merge to make it managed, then call EntMgr.remove to remove it

3) Create each new row by making a new Customer_Product, giving it a new PK object, filling in the PK's, and then calling EntMgr.persist

4) Close the transaction

This does not seem to work. On step 3, I keep getting errors saying that the new row(s) would create a duplicate key. This only happens if the new row happens to have the same PK's as a row that was supposedly deleted in step 2, but sometimes I need to re-add these. The entity manager does not seem to recognize that these have been deleted.

Where am I going wrong? I'm going crazy with this - any help would be greatly appreciated.

Thanks
Eric
James Sutherland
Ranch Hand

Joined: Oct 01, 2007
Posts: 553
Having two different objects with the same Id in the same persistence context or transaction is normally not a good idea in general.

Why removing the object if you are going to re-insert it? Maybe just remove the relations that you wish to remove.

You can first remove the old objects, call flush(), then add the new objects. Or use two separate transactions.

TopLink : EclipseLink : Book:Java Persistence : Blog:Java Persistence Performance
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Adding/deleting rows in many-to-many relationship