使用JPA实体管理器时,为什么要在删除之前进行合并? [英] When using JPA entityManager why do you have to merge before you remove?

查看:98
本文介绍了使用JPA实体管理器时,为什么要在删除之前进行合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直想知道为什么在使用JPA时,为什么必须编写这样的delete方法:

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));
    }
}

也许自从事务以这种方法开始和结束以来,就不需要包含了,但是我仍然想知道为什么删除不能只接受非托管对象.是因为需要对其进行管理才能知道该对象的ID是什么?任何其他见解都会很高兴听到.我只想了解删除JPA的方式和原因.

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.

推荐答案

删除操作可以级联到实体的关联.

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.

因此,如果它接受了一个分离的实体,则remove()必须为您做出决定:合并分离的实体并根据分离的实体包含的内容执行删除操作,或者简单地加载具有与分离实体相同ID的实体,并基于加载的实体执行操作.

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.

这篇关于使用JPA实体管理器时,为什么要在删除之前进行合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆