title: Resolving the JPA/Hibernate EntityNotFoundException
body: <p>I've run into a very weird situation here. When I try to delete a set of entities &amp; immediately later try to add another set of entities, which may or may not have the same elements again,I seem to be getting the below exception. The whole stack trace isn't required as it doesn't say much.</p>
  
  <pre><code>javax.persistence.EntityNotFoundException: deleted entity passed to persist [com.test.MyEntity#&lt;null&gt;]
  </code></pre>
  
  <p>To make myself more clear, let me give a more detailed explanation.</p>
  
  <p>This is my Entity.</p>
  
  <pre><code>@Entity
  @Table(name = "MY_ENTITY")
  @SequenceGenerator(name = "my_enty_seq", sequenceName = "MY_ENTITY_SEQ")
  public class MyEntity {
  
      private long id;
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO, generator = "my_enty_seq")
      @Column(name = "ID", unique = true, nullable = false, precision = 12, scale = 0)
      public long getId() {
          return this.id;
      }
  
      // Other methods &amp; variables which are not relevant here.
  }
  </code></pre>
  
  <p>And this is the class playing with the entities.</p>
  
  <pre><code>public class MyEntityServiceImpl implements MyEntityService {
  
      public void updateMyEntities(List&lt;MyEntity&gt; newEntities) {
  
          // Delete the Old Items
          List&lt;MyEntity&gt; oldEntities = myDAO.getAllEntities();
          myDAO.delete(oldEntities); // myDAO extends GenericDaoJpaWithoutJpaTemplate, hence, the DELETE is available in it.
  
          // Add the New Items
          myDAO.store(newEntities); // This is where I get the mentioned Exception.
      }
  
      // Other non-relevant stuffs
  }
  </code></pre>
  
  <p>The scenario where I get the mentioned exception on the <code>store()</code> method is when there is some common <code>MyEntity</code> object, present in both the <strong>oldEntities</strong> and <strong>newEntities</strong> lists.</p>
  
  <p>I've tried quite a few things to make this work, but nothing could help me overcome the problem. Adding <code>FetchType.EAGER</code> &amp; <code>CascaseType.ALL, CascaseType.PERSIST</code> also didn't work. The jpa <code>EntityManager</code> doesn't seem to have a <code>commit()</code> method either, which I could use after the <code>delete()</code> &amp; before the <code>store()</code> method. I've tried interchanging <code>store()</code> with <code>persist()</code>(though store internally calls <code>persist()</code>) too!</p>
  
  <p><strong>Note:-</strong> The requirement is to delete the old list and insert the fresh list, as comparing the elements and adding only the new ones is tedious(the list can be pretty huge at times).</p>