Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force an eager select in NHibernate

I am trying to eagerly fetch collections using selects, but all I am getting is inner joins. What is going on?

Session.CreateCriteria(typeof(Foo))
    .SetFetchMode("Bars", FetchMode.Select)
    .CreateAlias("Bars", "b")
    .SetFetchMode("b.Bazes", FetchMode.Select)
    .List();

I have tried changing FetchMode to Eager but that doesn't work - I still get inner joins instead of seperate selects. I'm not sure where it is even getting the inner join from, because nothing in the docs talks about FetchMode causing inner joins. Is it possible to get eager selects?

Update OK I worked out that creating an alias causes an inner join. So I can use .CreateAlias("Bars", "b", JoinType.None), but then the fetching of b.Bazes reverts to lazy loading. Urgh.

like image 573
cbp Avatar asked Dec 15 '09 04:12

cbp


1 Answers

An INNER JOIN is how NHibernate will load your records and their related child records. This is generally the most efficient way of doing it.

If it was to use multiple SELECT statements then the query for children would need to somehow include the criteria for the parent. An INNER JOIN makes it easy to get just related children, NHibernate will correctly split this out into multiple entities after running the query.

I believe Entity Framework 4 will let you do multiple queries and 'magically' re-attach related objects, but I'm not aware of NHibernate having such a feature (I'm sure someone will correct me if I'm wrong on this).

like image 90
Timothy Walters Avatar answered Sep 18 '22 13:09

Timothy Walters