Results 1 to 2 of 2
  1. #1
    mn1247 is offline Member
    Join Date
    Mar 2011
    Posts
    4
    Rep Power
    0

    Default Adding and deleting in many-to-many relationship

    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

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default

    Only delete the rows that are not in the new list.

    I suspect, until the transaction is committed, the check for PK is being done against the "real" data, not the in progress transaction data. Doesn't sound correct to me, though. I would have though the way you have done it would work.

Similar Threads

  1. help with mapping and relationship
    By peace76 in forum Enterprise JavaBeans (EJB)
    Replies: 5
    Last Post: 12-07-2010, 07:12 PM
  2. class relationship
    By RajShri in forum New To Java
    Replies: 2
    Last Post: 01-04-2010, 05:54 AM
  3. Deleting and Adding Lists in Java Applets
    By Bomber_Will in forum Java Applets
    Replies: 4
    Last Post: 11-28-2008, 06:52 AM
  4. How to update data for a JPA many-to-many relationship?
    By abhijit.sarkar in forum Enterprise JavaBeans (EJB)
    Replies: 1
    Last Post: 11-04-2008, 08:48 AM
  5. What is this Object relationship?
    By SirRawlins in forum New To Java
    Replies: 3
    Last Post: 12-14-2007, 03:17 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •