1 Reply Latest reply on Nov 17, 2005 6:39 AM by epbernard

    merge + persist

    redpoint7

      just a short understanding-question:

      User user =new User();
      user = em.merge(user);
      em.persist(user);
      System.out.println(user.getId());
      


      why do I have to use this "em.merge(user);" to create this Entity? If I leave this line out I get lots of exceptions:
      16:54:15,500 INFO [STDOUT] javax.ejb.EJBException: null; CausedByException is:
       detached entity passed to persist: com.example.entity.User
      16:54:15,501 INFO [STDOUT] at org.jboss.ejb3.tx.Ejb3TxPolicy.handleExceptionInOurTx(Ejb3TxPolicy.java:46)
      16:54:15,501 INFO [STDOUT] at org.jboss.aspects.tx.TxPolicy.invokeInOurTx(TxPolicy.java:70)
      16:54:15,502 INFO [STDOUT] at org.jboss.aspects.tx.TxInterceptor$Required.invoke(TxInterceptor.java:134)
      .....
      ....
      


      I simply don't understand, why I have to use it, cause in all the examples it isn't used at all ...

        • 1. Re: merge + persist
          epbernard

          The new user is considered detached because you probably have in your Db a user having the same id as the id set when the user is created.
          So merge actually update the user, and then since user is managed persist() is a no-op