When using JPA entityManager why do you have to merge before you remove?

▼魔方 西西 提交于 2020-01-01 08:53:41

问题


For a while now I have been wondering why when using JPA, do I have to write my delete methods like this:

@Transactional
public void delete(Account account)
{
    if (entityManager.contains(account))
    {
        entityManager.remove(account);
    }
    else
    {
        entityManager.remove(entityManager.merge(account));
    }
}

Perhaps the contains isn't needed since the transaction begins and ends with this method, but I still wonder why the remove couldn't just take an unmanaged object. Is it because it needs to be managed in order to know what the id is for that object? Any other insights would be great to hear. I just want to understand the hows and whys of the JPA remove.


回答1:


The remove operation can be cascaded to associations of an entity.

To be able to know which associated entities to remove, the entity manager can't rely on a detached entity, since, by definition, this detached entity doesn't reflect the latest state of the entity, and doesn't necessarily have all its cascaded associations recursively loaded.

So, if it accepted a detached entity, remove() would have to decide for you: either merge the detached entity and execute the remove operation based on what the detached entity contains, or simply load the entity having the same ID as the detached entity, and execute the operation based on the loaded entity.

Instead of deciding for you, it simply requires an attached entity. That way, you decide what you want.



来源:https://stackoverflow.com/questions/16086822/when-using-jpa-entitymanager-why-do-you-have-to-merge-before-you-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!