title: Why need detached entities in JPA?
body: <p>There are always so many questions related to issues with detached entities!</p>
  
  <p>First, they often cause <code>LazyInitializationException</code> in Hibernate.
  Yes, there are another persistence providers, which don't throw exceptions,
   but I think that they have some problems with consistency.
  Consider we have <code>A</code> and <code>B</code> entities that there is reference
  (<code>@ManyToOne</code>) from <code>A</code> to <code>B</code> that is required to be non-null.</p>
  
  <p>We started our session, loaded <code>A</code> instance and then closed session.
  After that we try to obtain a reference to <code>B</code>.
  And assume that another transaction just deleted both our <code>A</code> and <code>B</code> instances. So when we query from database we can't find appropriate <code>B</code> instance and get <code>null</code>!</p>
  
  <p>So our contract is violated. Some code that relies on fact that
  <code>a.getB()</code> returns an object will throw an <code>NullPointerException</code>.
  With persistent entities this is impossible because we have all lazy
  loading in the same transaction with obtaining object itself,
  so all operations are atomic (if we have a proper transaction isolation of course).</p>
  
  <p>Also there are problems when you want to store persistent and detached entities in one <code>Set</code>. It that case you should always override <code>equals</code> and <code>hashCode</code>, which usually looks awkward, as I can't see a really good way to do it.</p>
  
  <p>To get a detached entity back into <code>EntityManager</code> you should use <code>merge</code> which is glitchy.</p>
  
  <p>So my question is: is there is a reasonable scenario where detached entities are really needed? Furthermore, when do you have to mix detached and persistent entities
  and merge detached entities into a new <code>EntityManager</code>?</p>