0 Replies Latest reply on Apr 27, 2009 7:11 PM by Arbi Sookazian

    not using merge with SMPC

    Arbi Sookazian Master

      from SIA:



      Merging is a crude operation and should be avoided if possible. It first loads an entity
      instance with the same identifier as the detached instance into the current persistence
      context, resulting in a database read. Then, the property values from the detached
      instance are copied onto the properties of the managed instance. The main problem
      with this operation is that merging clobbers any changes that may have been made to
      the database record since the detached instance was retrieved (unless object versioning
      is used). There are other problems as well. If an entity instance with the same
      identifier as the detached instance has already been loaded into the current persistence
      context, a non-unique object exception is thrown because the uniqueness contract
      of entities in a persistence context is violated. You may also run into a lazy
      loading exception if you hit an uninitialized association on the detached instance during
      the merge. Avoid merging if at all possible.
      By using an extending persistence context, entity instances don’t become
      detached. Therefore, the persistence manager continues to track changes that are
      made to the entity. When it comes time to synchronize the entity with the database,
      calling the flush() method will do the trick within the scope of any transaction.


      @PersistenceContext(type = PersistenceContextType.EXTENDED)
      private EntityManager em;
      @End public void save() {
      em.flush();
      }



      So would it be safe to say that whenever using an EXTENDED PC (or SMPC), you should never use merge()?


      It seems that it was designed to be used in cases when the entities are detached, and when using SMPC, entities don't become detached...


      btw, in the code snippet above, how can you manually flush an EJB3 extended PC?  I thought manual flush was available via SMPC/Hibernate only...