1

I am trying to delete entity but I get this exception:

java.lang.IllegalArgumentException: Removing a detached instance

I understand that my problem is that I am using two different EntityManger instances. I looked out for a solution but all the solutions that I found was something like this:

entityManger.remove(entityManger.merge(entity));

There is another way to solve this issue instead of using merge and remove function?

Sagie
  • 996
  • 3
  • 12
  • 25

1 Answers1

2

Exception said that your entity is not managed by persistent context. You can not delete not managed entity. You can use

Entity entity = entityManager.getReference(Entity.class, id);
entityManager.remove(entity);

It is better, becouse you get lazy instance. Sorry for my english)

  • This is don't throw me exception but it dind't delete my entity, probably because I am doing getReference with one EntityManager and remove with other EntityManager. – Sagie Mar 08 '17 at 10:42
  • I dont know how it is possible) But use EntityManager which сontrols the entity you want to delete. And why do you have two EntityManager? You two DataBase? – Юлий Щербак Mar 08 '17 at 10:48
  • In one class I find the entity that I want to delete (First EntityManger). That class call to other class that there I actaully remove the object (Second EntityManger). – Sagie Mar 08 '17 at 11:59
  • Ok. As for me, the logic of the program is incorrect. You do not need to create multiple Entity Manager. Create one in a separate class and use it everywhere. And be sure to use transaction transactions. – Юлий Щербак Mar 08 '17 at 17:44
  • Yeah I changed a little bit of the architecture and used your solution. Thanks! – Sagie Mar 08 '17 at 20:54