In most examples of removing detached entities, the remove is usually paired with a merge:
em.remove(em.merge(detachedEntity));
My question is why is it not "more correct" to use find:
em.remove(em.find(Entity.class, detachedEntity.id));
or
em.remove(em.find(detachedEntity.getClass(), detachedEntity.id));
Is there a performance benefit over using merge?
In order to use EntityManager.remove() you need a managed entity. If you already have the detached entity, the easiest way is to call merge() to attach it to the persistence context. You could use find, but since the detached entity already contains the necessary information (class and id), there's no need to explicitly specify the class and retrieve the id.
You would only need find() if you didn't have the detached entity in the first place. So it's not "more correct" to use find() in this case, it's "more to type".
It might seem odd if you think of "merge" as "update", but it makes more sense when you think of it as "reattach" which it is in this case (and JPA thinks of it that way too, you often see the wording "merging back to the persistence context" which is not the same as "updating the entity in the DB" even though it may result in that...unless for example remove() is called afterwards).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With