2 Replies Latest reply on May 16, 2007 9:46 PM by waynebaylor

    Extended Persistence Context and merge()

      This is kind of a general question but is there ever a need to merge an entity when using an Extended Persistence Context? I guess the overarching question is do entities ever become detached in an extended pc? Being new to EJB3/JPA I am having trouble conceptualizing when to use persist() vs using merge(). I know that persist is usually thought of as an sql INSERT and merge is usually thought of as an sql UPDATE but does merge() ever call an INSERT? Are merge() and persist() interchangeable when dealing with new entities (or are they ever interchangeable)?

      Thanks for any help.

      -Brian

        • 1. Re: Extended Persistence Context and merge()
          radl01

          As you sead merge is used for detached objects and persist for atached ones.
          Short example for persist (update action)

          EntityManger em;

          .....
          Tab02000 recentRecord = (Tab02000)em.find(Tab02000.class, key);
          .. do some changes to recentRecord
          em.persist(recentRecord); // in this case JPA will call update action because you are changing existing object

          Short example for merge

          EntityManger em;
          Tab02000 newRecord = new Tab02000();
          ... set all values
          em.merge(newRecord);

          The second example is BAD PRACTISE of using JPA

          Jan

          • 2. Re: Extended Persistence Context and merge()
            waynebaylor

            merge() will figure out whether or not the entity passed is new or detached. If it's new then merge() will persist it (eventually resulting in an INSERT), otherwise it will update the DB with the current state of the entity (eventually resulting in an UPDATE).

            (warning: merging a removed entity will throw an exception)

            check these out for more info:

            http://www.hibernate.org/hib_docs/entitymanager/reference/en/html/objectstate.html
            section 3.6 and 3.7

            EJB3 Persistence Specification section 3.2.4.1