JPA thinks I'm deleting a detached object
I suspect that you are running your code outside a transaction so your find
and delete
operations occur in a separate persistence context and the find
actually returns a detached instance (so JPA is right and you ARE deleting a detached object).
Wrap your find / delete sequence inside a transaction.
Update: Below an excerpt of the chapter 7.3.1. Transaction Persistence Context:
If you use an
EntityManager
with a transaction persistence context model outside of an active transaction, each method invocation creates a new persistence context, performs the method action, and ends the persistence context. For example, consider using theEntityManager.find
method outside of a transaction. TheEntityManager
will create a temporary persistence context, perform the find operation, end the persistence context, and return the detached result object to you. A second call with the same id will return a second detached object.
public void remove(Object obj){
em.remove(em.merge(obj));
}
The above code is similar to that proposed by zawhtut
+1 to Pascal Thivent's post and just a followup.
@Transactional
public void remove(long purchaseId){
Purchase attached = jpaTemplate.find(Purchase.class,purchaseId);
jpaTemplate.remove(attached);
}