JPA/休眠-与孩子一起分离实体 [英] JPA/Hibernate - Detaching an entity along with children
问题描述
我正在将JPA 2与Hibernate 3.6.8一起使用.
I'm using JPA 2 with Hibernate 3.6.8 as the implementation.
假设我们有一个实体Foo
@Entity
public class Foo {
....
@OneToOne
private Bar bar;
....
}
我需要从会话中分离整个实体图,并且当我执行entityManager.detach(foo)
时,我惊讶地发现bar
仍保持连接状态,这与IMO相当不直观.
I need to detach the whole entity graph from the session, and when I do entityManager.detach(foo)
, I was surprised that bar
remained attached, which IMO is quite counter intuitive.
阅读EntityManager
上的文档,看来这是预期的情况,因为它没有提及任何与关联/子实体有关的内容:
Reading the documentation on the EntityManager
, it appears that this is the expected case since it does not mention anything about associations/child entites:
从持久性上下文中删除给定的实体,从而导致托管实体分离.对实体进行的未经修改的更改(包括删除实体)(包括删除实体)将不会同步到数据库.先前引用了分离实体的实体将继续引用它.
Remove the given entity from the persistence context, causing a managed entity to become detached. Unflushed changes made to the entity if any (including removal of the entity), will not be synchronized to the database. Entities which previously referenced the detached entity will continue to reference it.
我也可以简单地调用entityManager.detach(foo.getBar())
,但这意味着如果以后添加任何关联,我将必须确保也手动分离了这些关联.
I can simply call entityManager.detach(foo.getBar())
too, but it means that if I add any associations later on, I will have to make sure that those are detached manually too.
是否有任何简便的方法可以实现这一目标而无需依靠反思?
Is there any convenient way to achieve this without resorting to reflection?
推荐答案
添加DETACH类型的级联:
Add a cascade of type DETACH:
@OneToOne(cascade = CascadeType.DETACH)
private Bar bar;
这篇关于JPA/休眠-与孩子一起分离实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!