本文介绍了JPA/休眠-与孩子一起分离实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将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:

我也可以简单地调用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/休眠-与孩子一起分离实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 05:07