Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate - Detaching an entity along with children

I'm using JPA 2 with Hibernate 3.6.8 as the implementation.

Let's say we have an entity Foo

@Entity
public class Foo {
    ....
    @OneToOne
    private Bar bar;

    ....
}

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.

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.

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?

like image 469
Asa Avatar asked Jan 18 '12 07:01

Asa


1 Answers

Add a cascade of type DETACH:

@OneToOne(cascade = CascadeType.DETACH)
private Bar bar;
like image 65
JB Nizet Avatar answered Sep 20 '22 22:09

JB Nizet