public void edit(DiscountCode discountCode) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception { EntityManager em = null; try { utx.begin(); em = getEntityManager(); DiscountCode persistentDiscountCode = em.find(DiscountCode.class, discountCode.getDiscountCode()); Collection<Customer> customerCollectionOld = persistentDiscountCode.getCustomerCollection(); Collection<Customer> customerCollectionNew = discountCode.getCustomerCollection(); List<String> illegalOrphanMessages = null; for (Customer customerCollectionOldCustomer : customerCollectionOld) { if (!customerCollectionNew.contains(customerCollectionOldCustomer)) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add( "You must retain Customer " + customerCollectionOldCustomer + " since its discountCode field is not nullable."); } } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Collection<Customer> attachedCustomerCollectionNew = new ArrayList<Customer>(); for (Customer customerCollectionNewCustomerToAttach : customerCollectionNew) { customerCollectionNewCustomerToAttach = em.getReference( customerCollectionNewCustomerToAttach.getClass(), customerCollectionNewCustomerToAttach.getCustomerId()); attachedCustomerCollectionNew.add(customerCollectionNewCustomerToAttach); } customerCollectionNew = attachedCustomerCollectionNew; discountCode.setCustomerCollection(customerCollectionNew); discountCode = em.merge(discountCode); for (Customer customerCollectionNewCustomer : customerCollectionNew) { if (!customerCollectionOld.contains(customerCollectionNewCustomer)) { DiscountCode oldDiscountCodeOfCustomerCollectionNewCustomer = customerCollectionNewCustomer.getDiscountCode(); customerCollectionNewCustomer.setDiscountCode(discountCode); customerCollectionNewCustomer = em.merge(customerCollectionNewCustomer); if (oldDiscountCodeOfCustomerCollectionNewCustomer != null && !oldDiscountCodeOfCustomerCollectionNewCustomer.equals(discountCode)) { oldDiscountCodeOfCustomerCollectionNewCustomer .getCustomerCollection() .remove(customerCollectionNewCustomer); oldDiscountCodeOfCustomerCollectionNewCustomer = em.merge(oldDiscountCodeOfCustomerCollectionNewCustomer); } } } utx.commit(); } catch (Exception ex) { try { utx.rollback(); } catch (Exception re) { throw new RollbackFailureException( "An error occurred attempting to roll back the transaction.", re); } String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { Character id = discountCode.getDiscountCode(); if (findDiscountCode(id) == null) { throw new NonexistentEntityException( "The discountCode with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } }