title: JPA/Hibernate Parent/Child relationship
body: <p>I am quite new to JPA/Hibernate (Java in general) so my question is as follows (note, I have searched far and wide and have not come across an answer to this):</p>
  
  <p>I have two entities:</p>
  
  <p>Parent and Child (naming changed).</p>
  
  <p>Parent contains a list of Children and Children refers back to parent.</p>
  
  <p>e.g.</p>
  
  <pre><code>@Entity
  public class Parent {
  
  @Id
  @Basic
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "PARENT_ID", insertable = false, updatable = false)
  private int id;        
  
      /* ..... */
  
      @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
      @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", nullable = true)
      private Set&lt;child&gt; children;
  
      /* ..... */
  
  }
  
  @Entity
  public class Child {
  
  @Id
  @Basic
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "CHILD_ID", insertable = false, updatable = false)
  private int id; 
  
      /* ..... */
  
      @ManyToOne(cascade = { CascadeType.REFRESH }, fetch = FetchType.EAGER, optional = false)
  @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
  private Parent parent;
  
      /* ..... */
  
  }
  </code></pre>
  
  <p>I want to be able to do the following:</p>
  
  <ol>
  <li><p>Retrieve a Parent entity which would contain a list of all its children (List), however, when listing Parent (getting List, it of course should omit the children from the results, therefore setting FetchType.LAZY.</p></li>
  <li><p>Retrieve a Child entity which would contain an instance of the Parent entity.</p></li>
  </ol>
  
  <p>Using the code above (or similar) results in two exceptions:</p>
  
  <ol>
  <li><p>Retrieving Parent:
  A cycle is detected in the object graph. This will cause infinitely deep XML...</p></li>
  <li><p>Retrieving Child:
  org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: xxxxxxxxxxx, no session or session was closed</p></li>
  </ol>
  
  <p>When retrieving the Parent entity, I am using a named query (i.e. calling it specifically)
      @NamedQuery(name = "Parent.findByParentId", query = "SELECT p FROM Parent AS p LEFT JOIN FETCH p.children where p.id = :id")</p>
  
  <p>Code to get Parent (i.e. service layer):</p>
  
  <pre><code>public Parent findByParentId(int parentId) {
      Query query = em.createNamedQuery("Parent.findByParentId");
      query.setParameter("id", parentId);
  
      return (Parent) query.getSingleResult();
  }
  </code></pre>
  
  <p>Why am I getting a LazyInitializationException event though the List property on the Parent entity is set as Lazy (when retrieving the Child entity)?</p>