2

I am learning JPA Entity life cycle and i want to understand the 'Detached' entities. Below is my code,

//Creating a new employee with id and name field
Employee e = new Employee("1001","Sasi");
   em.getTransaction().begin();
       em.persist(e);
   em.getTransaction().commit();
//Detaching Employee from Persistence context
em.detach(e);
//Persisting detached entity
   em.getTransaction().begin();
       e.setEmployeeId("1002");
       em.persist(e);
   em.getTransaction().commit();

What i am seeing is, there are two rows inserted in to mysql database instead of getting an error. Could you please let me know why error is not thrown? I am sure that i misunderstood the concept of detached entities and kindly help me in understanding it correctly.

JPS
  • 2,730
  • 5
  • 32
  • 54

2 Answers2

1

Entities are identified by their IDs not by the object instance. So, if you give the entitiy a new id ("1002" in this case) it's a new entity that can be persisted without errors. You detached an entity with the ID "1001". But that does not affect the entity with ID "1002".

BTW Detaching means you removed the entity from the context, which means the entity manager looses the control over the respective object instance. So, e.g. it can not reload lazy declared OneToMany refrences/lists, a.s.o. If you have a entity with a new ID, you can persist it. If you have an entity with a already persisted ID you must merge/attache it, then you can persist the attached object, which means you update the persistent entity.

Peter Paul Kiefer
  • 2,114
  • 1
  • 11
  • 16
  • Could you please tell me when will I get "cannot persist detached object" error? – JPS Jul 25 '15 at 08:42
  • Do not set a new ID to the detached entity of your example before you persist it. And use persist as you did it and _not_ merge. I'm not sure that you will get this error message, but it's the only way where I would expect it. – Peter Paul Kiefer Jul 25 '15 at 10:29
  • If i do that, i will be getting 'Duplicate Key error' instead of entity detached error. – JPS Jul 25 '15 at 10:39
  • 1
    It's been a long time since I'd worked with JPA. I googled and found an Interesting link http://www.objectdb.com/java/jpa/persistence/detach. E.g. `em.lock(entity)` could throw the error if entity was detached. – Peter Paul Kiefer Jul 25 '15 at 12:45
1

I have a unclear observation, (in web app, detached entities are hard to debug), maybe Eslipelink 2.6 silently save existing detached object twice at new Id (by em.persist() ). No Exception, nothing, silence. Surprise for me.

When I change to update() +persist() all OK.

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22