Dynamic Eager & Lazy Loading in Hibernate
<p>I'm new to Hibernate, but have plenty of experience with the Entity Framework in C#. One feature I love is the ability to dynamically decide what to load immediately in a query. For example, consider a One-to-Many relationship of Class and Student Entities.</p>

<p>On a "View Classes" page I can do this:</p>

<pre><code>context.Configuration.EnableLazyLoading = true; //default option
List&lt;Classes&gt; classes = context.Classes.ToList();
</code></pre>

<p>Now I can happily just show the class info, without wasting resources gathering student data. ONLY when the user clicks the "View Classes with Rosters" do I do the following:</p>

<pre><code>context.Configuration.EnableLazyLoading = true;
List&lt;Classes&gt; classes = context.Classes.Include(c =&gt; c.Students).ToList();
</code></pre>

<p>With that one statement, I was able to decide that in this particular situation, I want to grab all the info at once. Not two queries. Not one-hundred queries. Just one query. All despite loading only the classes a few seconds prior.</p>

<p>All of my reading on Hibernate explains how you can specify lazy="true|false" in the configuration files of relationships, but I really want the option of deciding when to load collections on the fly. After all, I'm not interested in buying a car that only goes either 30mph or 60mph. I need to choose a speed depending on where I am.</p>

<p>Perhaps the option of using fetch mode as JOIN is acceptable in that it will only be two queries in this situation (one for the class, and one for the students), but I really liked having the option of doing it all in one query, especially if I have several child collections to load and don't want to perform a query per relationship. I realize the all-at-once joins create extra data that needs to be streamed, but I'm surprised that this level of control isn't easily done or may be unavailable entirely.</p>