title: Clearing the JPA or Hibernate EntityManager or merge the entity before remove operation
body: <p>I have a generic JPA repository implementation dealing with many type of entities as follows:</p>
  
  <pre><code>@Component
  @Transactional(transactionManager = "ubldbTransactionManager")
  public class CatalogueRepositoryImpl {
  ...
  
      @PersistenceContext(unitName = eu.nimble.utility.Configuration.UBL_PERSISTENCE_UNIT_NAME)
      private EntityManager em;
  
      public &lt;T&gt; void deleteEntity(T entity) {
          if(!em.contains(entity)) {
              entity = em.merge(entity);
          }
          em.remove(entity);
      }
  
      public &lt;T&gt; List&lt;T&gt; getEntities(String queryStr) {
          Query query = em.createQuery(queryStr);
          List&lt;T&gt; result = query.getResultList();
          return result;
      }
  ...
  }
  </code></pre>
  
  <p>At some point I realized that some of the entities have not been deleted. Then, I found out that some <code>managed</code> entities cause cancellation of the removal, as described at: <a href="https://stackoverflow.com/a/16901857/502059">https://stackoverflow.com/a/16901857/502059</a></p>
  
  <p>Since the method is generic, it included various types of entities inside. As a work around, I wanted to get rid of the entities causing cancellation of deletion and I added <code>em.flush()</code> and <code>em.clear()</code> at the beginning of the <code>deleteEntity</code> method. Although this worked, I feel that this is a dirty workaround. </p>
  
  <p>So, I'm asking some best practices for such a case. For example, would creating a new <code>EntityManager</code> in <code>deleteEntity</code> be an alternative? I didn't want this since I wanted Spring to handle managing the scope of <code>EntityManagers</code> and <code>transactions</code>.</p>
  
  <p><strong><em>One last point about Spring-managed EntityManager</em></strong>: I also wonder whether the <code>em</code> in the example managed by Spring is an application-scope one? If so, wouldn't it keep all the retrieved entities and expand continuously? </p>