title: JPA confusion (managed vs non-managed entities)
body: <p>I'm working on a web project, trying to understand the best way to do this sort of thing over and over again:</p>
  
  <ul>
  <li>Read object <strong>A</strong> from the DB</li>
  <li>Later on, read another object (<strong>B</strong>)</li>
  <li>Make changes to <strong>A</strong> and <strong>B</strong> in the DB (as part of a transaction - write <strong>all</strong> the changes or none)</li>
  </ul>
  
  <p>The old-skool JDBC-type way isn't a problem, but JPA is doing my head in.</p>
  
  <p>I need there to be a clear demarcation as to where the DB changes occur, and from what I've observed any changes to managed entities will be modified the next time <code>EntityManager.commit()</code> is called (no matter if a transaction was explicitly begun before the changes or not). Correct?</p>
  
  <p>Is it better then to make sure all entities are <strong>never</strong> managed, and always <code>merge()</code>?</p>
  
  <p>I find myself having to decide between these two examples:</p>
  
  <p><strong>RepaintAction1</strong></p>
  
  <pre><code>User user = getUser(); //non-managed entity
  Car car = getCar(123); //non-managed
  
  car.setColor("Red");
  user.setLog("Paints car red");
  
  dao.update(car, user);
  </code></pre>
  
  <p><strong>RepaintDAO1</strong></p>
  
  <pre><code>entityTransaction.begin();
  entityManager.merge(car);
  entityManager.merge(user);
  entityTransaction.commit();
  </code></pre>
  
  <p>Or:</p>
  
  <p><strong>RepaintAction2</strong> (this is the same as <strong>RepaintAction1</strong>, but with <strong>managed</strong> entities)</p>
  
  <pre><code>User user = getUser(); //managed entity
  Car car = getCar(123); //managed
  
  car.setColor("Red");
  user.setLog("Paints car red");
  
  dao.update(car, user);
  </code></pre>
  
  <p><strong>RepaintDAO2</strong></p>
  
  <pre><code>entityTransaction.begin();
  entityManager.flush();
  entityTransaction.commit();
  </code></pre>
  
  <p>The first I don't mind, but I must be missing some advantages to managed entities (which ones?). In the second I don't like the way the scope of transactions is not clear (and how is a rollback handled?).</p>
  
  <p>But are these the only options (e.g. is there a way to clearly demarcate transactions using managed entities)? What is the best way to handle this?</p>
  
  <p>I apologise for making this long, but I've gone through a lot of documentation that hasn't helped and I'm not even sure that what I'm observing is correct.</p>