Search code examples
javaspringhibernatesql-deletehibernate-entitymanager

Delete entity while using two instances of EntityManger


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?


Solution

  • 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)