title: merge vs find to update entities JPA
body: <p>From the book <strong>Pro EJB3 JPA</strong>:</p>
  
  <blockquote>
    <p>The most common strategy to handle this (-update entities-) in Java EE application that uses JPA is to place the results of the changes into detached entity instances and merge the pending changes into a persistence context so that they can be written to the database</p>
  </blockquote>
  
  <p>Example: 
  <em>The <strong>emp</strong> param is a detached entity</em></p>
  
  <pre><code>@Stateless
  public class EmployeeServiceBean {
      @PersistenceContext
      EmtityManager em;
  
      public void updateEmployee(Employee emp){
         if(em.find(Employee.class, emp.getId()) == null){
             throw new IllegalArgumentException("Unknown Employee id")
         }
  
         em.merge(emp);
      }
  }
  </code></pre>
  
  <p>Then, says:</p>
  
  <blockquote>
    <p>If the amount of information being udated is very small, we can avoid the detached object and merge() operation entirely by locating the managed version and manually copying the changes into it.</p>
  </blockquote>
  
  <p>Example: 
  <em>Here the <strong>emp</strong> is attached</em></p>
  
  <pre><code>public void updateEmployee(int id, String newName, long newSalary) {
      Employee emp = em.find(Employee.class, id);
      if(emp==null){
          throw new IllegalArgumentException("Unknown Employee id")
      }
      emp.setEmpName(newName);
      emp.setSalary(newSalary);
  }
  </code></pre>
  
  <p>So, looks like for small updates and create operations the strategy <code>find()</code> and then set new values one by one is convenient. But!, for big updates of data (i.e collections) is preferred have a detached entity and all it's relations (with CascadeType.Merge) and do a big <code>merge()</code>.</p>
  
  <p>OK, but <strong>why</strong>?</p>