title: Spring and Hibernate: DAO Pattern. How to solve LazyInitializationException
body: <p>I'm wondering: What is the point of <code>FetchType.LAZY</code> in one(many)-to-many using DAO Pattern?
  It is basically useless? As soon as you are outside of your DAO (eg. were the actual work is done) you can't fetch the related data as you are not in a hibernate session anymore.</p>
  
  <p>Lets make an Example:</p>
  
  <p><code>Student</code> and <code>Class</code>. A student takes many classes. he now logs into the system and his Student entity object is retrieved from the system.</p>
  
  <pre><code>application layer -&gt; Service Layer -&gt; DAO
  </code></pre>
  
  <p>Now the Student wants to see which classes he takes and oops a <code>LazyInitializationException</code> occurs as we are outside of DAO.</p>
  
  <p>What are the options to prevent this? I've like googled hours and not found a solution for this except to actually fetch everything before leaving the DAO which defeats the purpose of lazy in the first place. (Have read about <code>OpenSessionViewFilter</code> but this should work independent of the application layer)</p>
  
  <p>How do you solve this issue in a good way? What are alternative patterns that don't suffer from this?</p>
  
  <p>EDIT:</p>
  
  <p>I get no <code>LazyInitializationException</code> with following settings:</p>
  
  <pre><code>@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.compound", 
          cascade = CascadeType.ALL, orphanRemoval = true)
  @Fetch(FetchMode.JOIN)
  </code></pre>
  
  <p>Funny thing is it must be exactly like this. </p>
  
  <p>removing <code>@Fetch</code> -> <code>LazyInitializationException</code></p>
  
  <p>Even stranger is if I remove <code>orphanRemoval = true</code>, then <code>LazyInitializationException</code> also occurs even with <code>@Fetch</code>. So both of those are required. </p>
  
  <p>Maybe someone could enlighten me why this is the case. Currently I'm tending to ditch hibernate completely as with pure JDBC I would have reached the desired behavior hours ago...</p>