Without explicit declaration, the default loading behavior in NHibernate is lazy-loading, where data does not get loaded till the object or property is evaluated.  In other words, the load is on-demand.  This lessens a lot of unnecessary I/O and memory overhead in many cases, but in some scenario, an uncareful programmer may loop through a list of children referring to a parent, thus parent keeps getting loaded each time the property is called.  Imagine if there are 1,000 children with 500 unique parents, that means the database gets called 501 times just to loop through the children.

In the scenario above, eager loading comes in handy.  Below are set up’s of two most commonly used eager loading scenario.  They aren’t necessarily confined within the parent-to-child relationship.

Many-to-One

For example, a child may contain reference to Parent through parentId, in child’s mapping file, add the fetch=”join” option:

<many-to-one name="Parent" column="parentId" class="Child" fetch="join" />

One-to-Many

In situation where Parent may contain a property (usually a collection) referring to a list of children, in its XML mapping, it could be stated as

<bag name="Children" inverse="true" lazy="false" cascade="all-delete-orphan">
   <key column="parentId" />
   <one-to-many class="Child" />
</bag>

in the entity class declaration of parent, it could be written as

public virtual IList Children
{
get { return children; }
set { children = value; }
}
public virtual void AddChild(Child child)
{
child.Parent = this;
if (Children == null)
Children = new List();
Children.Add(child);
}

Advertisements