title: JPA/Hibernate - Detaching an entity along with children
body: <p>I'm using JPA 2 with Hibernate 3.6.8 as the implementation.</p>
  
  <p>Let's say we have an entity <code>Foo</code></p>
  
  <pre><code>@Entity
  public class Foo {
      ....
      @OneToOne
      private Bar bar;
  
      ....
  }
  </code></pre>
  
  <p>I need to detach the whole entity graph from the session, and when I do <code>entityManager.detach(foo)</code>, I was surprised that <code>bar</code> remained attached, which IMO is quite counter intuitive.</p>
  
  <p>Reading the documentation on the <code>EntityManager</code>, it appears that this is the expected case since it does not mention anything about associations/child entites:</p>
  
  <blockquote>
    <p>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. </p>
  </blockquote>
  
  <p>I can simply call <code>entityManager.detach(foo.getBar())</code> too, but it means that if I add any associations later on, I will have to make sure that those are detached manually too. </p>
  
  <p>Is there any convenient way to achieve this without resorting to reflection? </p>