Changing LazyLoad Initial Behavior in NHibernate

I just started using NHibernate and fluent-NHibernate, which I think are great. I configured all my mappings to use LazyLoading for any relationship between classes, because, as a rule, I believe that it is not necessary to load everything in advance. However, sometimes you know that 100% you will load all relations or at least one relation, and it will save additional connections if you receive data ahead.

In any case, can you tell NHibernate to load relationship data for the relationship and override the initial setting?

I used LinqToSql before, for this I would create repositories that would overload what the elements should load, in what respects, when necessary. This worked very well, so I would like something similar for NHibernate.

+4
source share
2 answers

I found that this could use the LazyLoading / Eager download function for NHibernate queries.

Create your ICriteria in the usual way, and then the name of the association (relationship property, for me, the price), and then the type of selection that can be combined, select, lazyload, eagerly

.SetFetchMode("Prices", FetchMode.Join) 
+7
source

If you are doing HQL, you can use the “left outer join” or “left join” to join the association you want, rather than lazy loaded ones, for example.

If you have a Building class that has a property that returns an Address object, and this relationship will be lazy, you can have HQL similar to:

 string hql = "from Building bld where bld.Type.Id = 1"; 

When using the Address property, a different SQL statement will be executed for each building. Changing HQL to the following will extract the addresses as part of the original SQL statement:

 string hql = "from Building bld left outer join fetch bld.Address as addr where bld.Type.Id = 1"; 
0
source

All Articles