Sunday, March 09, 2008

JPA Error (on delete) : java.lang.IllegalArgumentException: Removing a detached instance

This is a problem I got while deleting a record.

What I've figured is that you cannot delete a persistent object that you got very earlier (ex: as a result of a relationship of another object)

What's needed to be done is to refetch that object again by using find and delete it.

Solution:
EntityManager em=CWUtil.getEntityManager();
em.getTransaction().begin();
m=em.find(Membership.class, m.getId()); //<-Fetched again here
em.remove(m); //<-Deleted here
em.getTransaction().commit();
em.close();


Solves the problem!

2 comments:

João Paulo Carvalho said...

Thank u!

I'd like to comment that I finded other solution: entityManager.lock(object, lockMode) but it's to Persistent objetcs..

Using find() the object turn to Persistent and finally can be deleted()

João Paulo Carvalho
joaopaulo@bemmelhor.com.br
joao_paulo_carvalho@yahoo.com.br

Ondrej Medek said...

Well, this solution generates one more extra SQL query and bypasses the optimistic locking. So I do not know the "proper" solution, but I do not recommend this one.