Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding/deleting rows in many-to-many relationship

 
Eric Jones
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic