title: Best ways to use the lazy load
body: <p>I have a very long chain of objects, all of which will be loaded lazily. We use JPA(out of luck on fetchmodes)</p>
  
  <p>In a few cases we dont have to load full object graph, in these cases the performance is good. But in few other cases, we might have to load a full object Graph like below. </p>
  
  <p><strong>Below classes are for representational purpose only</strong></p>
  
  <pre><code>FirstObject.java
  
  @Lazy
  private Set&lt;SecondObject&gt;
  </code></pre>
  
  <hr>
  
  <pre><code>SecondObject.java    
  @Lazy
  private Set&lt;ThirdObject&gt; // may load 20-30 objects
  @Lazy
  private Set&lt;FourthObject&gt; // may load 20-30 objects
  </code></pre>
  
  <hr>
  
  <pre><code>ThirdObject.java
  @Lazy
  private Set&lt;FourthObject&gt; // may load 10 - 100 records
  </code></pre>
  
  <hr>
  
  <pre><code>FourthObject.java
  @Lazy
  private Set&lt;FifthObject&gt; // may load 10-100 records
  </code></pre>
  
  <p>.<br/>
  .<br/>
  .<br/>
  (the list goes on)</p>
  
  <p><strong>Edge case</strong></p>
  
  <p>If you see, each child loads several children and there is no way to avoid. Imagine the user is trying to load the Firstobject.java now and he needs full object graph until the FifthObject.java graph.</p>
  
  <pre><code>firstObject = session.get(FirstObject.class, 10);
  </code></pre>
  
  <p>//Because all the children are lazy, he tries to initialize them like below.</p>
  
  <pre><code>firstObject.getSecondObject().size() // size() for load all the lazy children
  </code></pre>
  
  <p>//Now each of the child is a collection and they are lazy so he has to do the following</p>
  
  <pre><code>for(SecondObject sec: firstObject.getSecondObject()){
      sec.getThirdObject().size();
     //because third object needs fourth object we loop third and get all ffourth
  }
  </code></pre>
  
  <p>All the above code takes around 7-10 seconds to run, and may be more if the children are more. </p>
  
  <p>Question is, How do I load objects in this case? the user interaction is so erratic, that we may or may not need full graph. </p>
  
  <p>I've thought about using custom JPQL/native SQL which joins all the related children and return Entity objects as one option, but wondering if all the effort is good. </p>
  
  <p>Note: the user may not need all the information that is returned in the object graph, but, he needs only a couple of properties for display purpose(but he needs all objects though). </p>