views:

234

answers:

1

Given an object hierarchy such as the following:

class Category
{
    List<SubCategory> SubCategories;
}

class SubCategory
{
    List<Product> Products;
}

class Product
{
}

Is it possible to eager load the whole hierarchy using NHibernate? I would like to execute one query to load all categories with subcategories and products eager loaded.

+1  A: 

Yes , it is possible ... However, don't you think that this will have some performance implications ? It is possible that you retrieve a huge amount of data.

in order to do it, you'll have to use the 'SetFetchMode' method of the ICriteria that you'll use to retrieve the instances.

Something like this:

ICriteria crit = session.CreateCriteria (typeof(Category));

crit.SetFetchMode ("SubCategories", FetchMode.Eager);

Or, maybe by using CreateAlias:

ICriteria crit = session.CreateCriteria (typeof(Category));

crit.CreateAlias ("SubCategories", "sc", JoinType.LeftOuterJoin);
crit.CreateAlias ("sc.Products", "p", JoinType.InnerJoin);

perhaps you'll have to play a bit with the possible JoinTypes, depending on your situation / what you want.

Frederik Gheysels