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?
Add a cascade of type DETACH:
@OneToOne(cascade = CascadeType.DETACH)
private Bar bar;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With