title: How do I make my entity object managed so I can remove it?
body: <p>This doesn't work -- I always get the IllegalArgumentException thrown with the advice to "try merging the detached and try the remove again."</p>
  
  <pre><code>@PersistenceContext private EntityManager   em;
  @Resource           private UserTransaction utx;
  public void delete(EN entity) {
      if (entity == null) return;   // null-safe
      EN target = entity;
      try {
          if (!em.contains(entity)) {
              System.out.println("delete() entity not managed: " + entity);
              utx.begin();
              target = em.merge(entity);
              utx.commit();
              System.out.print("delete() this entity should now be managed: " + em.contains(target));
          }
          utx.begin();
          em.remove(target);
          utx.commit();
      } catch (RollbackException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (HeuristicMixedException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (HeuristicRollbackException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (SecurityException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalStateException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (NotSupportedException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      } catch (SystemException ex) {
          Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
      }
  }
  </code></pre>
  
  <p>The output log shows the following:</p>
  
  <pre><code>INFO: delete() entity not managed: com.database.SomeTable[ id=2 ]  
  INFO: delete() this entity should now be managed: false
  </code></pre>
  
  <p>In other words the <strong>merge()</strong> does not return a managed entity.   Can anyone spot what I did wrong?</p>
  
  <p>Second question: is there a way to do this in one transaction rather than two?</p>
  
  <p>This is with EclipseLink inside GlassFish 3.1.</p>