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