Skip to content
Advertisement

What is the difference between em.remove(st) and em.remove(em.contains(st) ? st : em.merge(st));

I was getting this error:

java.lang.IllegalArgumentException: Removing a detached instance model.student

Then I search for it in stackoverflow and I found this solution:

instead of:

em.remove(student); 

I am using now:

em.remove(em.contains(student) ? student : em.merge(student));

But I really didn’t get why is it working now.

Can someone tell me the diffrence between this methods?

Advertisement

Answer

@ why is it working now, EntityManager works only with ManagedEntities. When you try to remove an entity which is detached already, you will get an exception.

So to make a safe remove, you have to check first the entity is in managed state or not. that is achieved by em.contains method.

And if that entity is not in the managed state yet, we need to manually move that to managed state. This can be achieved by using, merge.

Merge basically moves that entity to the managed state.

[Edit]

I can see in your code that you’ve retrieved the entity using em.find which would give you an managed entity. But you’ve not stored that value to anything and used the method’s input parameter which is not managed by em. Try the following code,

`public void deleteStudentsPersistence(Student student) {
    Student managedEntity = em.find(Student.class, student.getId());
    em.remove(managedEntity);
   // em.remove(em.contains(student) ? student : 
   // em.merge(student));
}`
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement