Eager fetching
You can disable lazy loading in mapping and that would load all collections/associations eagerly all the time. But as stated earlier, eagerly loading associations all the time is not a good idea. However, at times you do need to load a particular association eagerly. For this reason, NHibernate lets you specify, during the query, that a particular association should be loaded eagerly. Let's take a look at examples of different querying mechanisms to see how to eagerly load associations.
HQL
To eagerly load associations in HQL, you need to add keyword fetch
after the join
keyword, as shown next:
select e from Employee as e join fetch e.Benefits where e.Firstname = :firstName
Preceding HQL query loads all employee instances with matching first name and also loads their Benefits
collection in the same select eagerly.
Criteria
Criteria API offers a method named SetFetchMode
that can be used to tell NHibernate of our intent to load a particular association eagerly. Following example...