title: Hibernate lazy fetch - getting child objects
body: <p>My understanding is that, by default, Hibernate will set the FetchType to lazy, for all relation types.</p>
  
  <p>In my case, I have a bi-directional OneToMany-ManyToOne relationship, as follows:</p>
  
  <p>Parent class:</p>
  
  <pre><code>public class Parent{
  
      @Id
      @Column(name = "parent_id")
      private long parentId;
  
      @OneToMany(mappedBy = "parent")
      @JsonIgnore
      private List&lt;Child&gt; children;
  
      public List&lt;Child&gt; getChildren()
      {
          return this.children;
      }
  }
  </code></pre>
  
  <p>Child class:</p>
  
  <pre><code>public class Child
  {
      private String name;
  
      @ManyToOne(optional = false) //every child must have a parent
      @JoinColumn(name = "parent_id")
      private Parent parent;
  
      public Child(Parent parent, String name)
      {
          this.parent = parent;
          this.name = name;
      }
  }
  </code></pre>
  
  <p>Child service:</p>
  
  <pre><code>public class ChildService
  {
      public List&lt;Child&gt; getChildren(long parentId)
      {
          Parent parent = getParentRepository().findOne(parentId);
          return parent.getChildren(); //This returns null
      }
  
      public Child getNamedChild(long parentId)
      {
          Parent parent = getParentRepository().findOne(parentId);
          //??????????????? 
          //Not sure how to get the children of this specific parent, 
          //which has a specific name.
      }
  }
  </code></pre>
  
  <p>Parent repository:</p>
  
  <pre><code>public interface ParentRepository extends JpaRepository&lt;Parent, Long&gt; {
  }
  </code></pre>
  
  <p>I have two problems here:</p>
  
  <p>When I call the method getChildren() in ChildService, it returns null. The database does contain the right data.
  I will need to get these with LAZY fetch type.
  I have tried to invoke a "parent.getChildren().size()" method, before returning, but it still returns null.</p>
  
  <p>The other problem is how do I get a child that has a specific name? Is it possible to do it via the Repository? Or do I need to getChildren(parentId), and iterate until I find the one that is named in a specific way?</p>
  
  <p>EDIT:
  After some suggestions, I went on and implemented my ChildRepository this way:</p>
  
  <pre><code>public interface ChildRepository extends JpaRepository&lt;Child, Long&gt; {
      @Query("SELECT child FROM Parent parent JOIN parent.child AS child WHERE parent.parentId = :parentId")
      List&lt;Child&gt; getChildren(@Param("parentId") String parentId);
      @Query("SELECT child FROM Parent parent JOIN arent.child AS child WHERE parent.parentId = :parentId AND child.childId = :childId")
      Child getChildByName(@Param("childId") Long childId, @Param("parentId") String parentId);
  }
  </code></pre>