title: Best way to handle JPA merge?
body: <p>I'm new to the whole JPA thing so I have multiple questions about the best way to handle JPA merge and persist.</p>
  
  <ol>
  <li><p>I have an user object which should be updated (some values like date and name). Do I have to merge the passed object first or is it safer to find the new object?</p>
  
  <p>Currently my code for updating a user looks like this: </p>
  
  <pre><code>public void updateUserName(User user, String name) {
       // maybe first merge it?
       user.setName(name);
       user.setChangeDate(new Date());
       em.merge(user);   
   }
  </code></pre>
  
  <p>How can I be sure that the user has not been manipulated before the update method is called? Is it safer to do something like this:</p>
  
  <pre><code> public void updateUserName(int userId, String name) {
       User user = em.getReference(User.class, userId);
       user.setName(name);
       user.setChangeDate(new Date());
       em.merge(user);   
   }
  </code></pre>
  
  <p>Maybe other solutions? I watched multiple videos and saw many examples but they all were different and nobody explained what the best practice is.</p></li>
  <li><p>What is the best approach to add children to relationships? For example my user object has a connection to multiple groups. Should I call the JPA handler for users and just add the new group to the user group list or should I create the group in a so group handler with persist and add it manually to my user object?</p></li>
  </ol>
  
  <p>Hope somebody here has a clue ;) </p>