Monday, September 15, 2008

JPA: java.lang.IllegalArgumentException: Removing a detached

One of the common issues that I end up debugging is the following exception:

java.lang.IllegalArgumentException: Removing a detached instance

When does this occur?: While removing a record.
Why does this occur?: You are trying to delete a record which is retrieved in another transaction (probably even trying to delete a record that is stored in user HTTP session).
How to fix it?: Make sure you retrieve the record in the same transaction. Sample code for the same:

  1. public void removeOrganization(Organization org) {  
  2.     if (org.getId() != null) {  
  3.         org=em.find(Organization.class, org.getId());  
  4.         em.remove(org);       
  5.     } else {  
  6.        // your error logic.  
  7.     }  
  8. }  

1 comment:

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.