title: How to properly refresh a stale entity from a database?
body: <p>In my web application I often need to keep entities read from the database  over the span of a single request and refresh them later in another request. Currently I have a helper method</p>
  
  <pre><code>protected &lt;T&gt; T refresh(T t) {
      if (!entityManager.contains(t)) {
          t = merge(t);
          entityManager.refresh(t);
      }
      return t;
  }
  </code></pre>
  
  <p>Each method them refreshes the entity it's working on before anything else. If the entity has already been refreshed, nothing happens.</p>
  
  <p>This worked nicely, until later I realized that this solution has a significant problem: <strong>The call to <code>merge</code> fails if the entity has been concurrently modified in the database.</strong> Obviously <code>merge</code> can't "know" that the content of <code>t</code> will be replaced anyway by the immediate call to <code>refresh</code>.</p>
  
  <p>What would be the proper solution to this problem? So far I have these ideas, none of which feels completely satisfactory:</p>
  
  <ol>
  <li><p>Instead of calling <code>merge</code> and <code>refresh</code>, get the ID of the entity and call</p>
  
  <pre><code>t = find(theClassOfT, t.getId());
  </code></pre>
  
  <p>This would solve the problem, I'd get a fully fresh entity, but it has a major drawback: I need to know the class of <code>T</code> and it's ID. Getting the ID can be accomplished by a having a top super-interface for all my entities, but getting the class is problematic (since a JPA implementation may subclass the entities, I'm afraid that calling <code>t.getClass()</code> could return some implementation specific subclass of <code>T</code>).</p></li>
  <li>Keep only IDs in the long term and read entities fresh during each request. This seem more correct from the design point of view (stale entities carry invalid information anyway), but again requires to have the class of <code>T</code> at hand.</li>
  </ol>
  
  <p><strong>Update:</strong> The reason I'm keeping the entities across the requests is merely for convenience. I specifically don't need to ensure that the entity isn't modified during that time - I refresh it at the next request anyway.</p>