NHibernate When to use lazy loading?

All I understand about lazy loading is that it is loaded only when an object is needed and we have to use it. Please explain to me what scripts should we use and not use? Thanks in advance.

+3


source to share


2 answers


I would say this:

Lazy loading is the essence of ORM. This is the ORM principle. (if we don't want to load the full DB in one shot)

Check out this article by Ayende:

NHibernate is lazy, just live with it

small quote from this source:



... There is a good reason why lazy is set to true by default, and while I'm sure there are some limited number of scenarios where lazy = "false" is an appropriate choice, this is not for your scenario ...

From my experience:

I could hardly explain it better than this post by Ayende. But I have to confirm - I see the same thing. I've never used lazy setup. If something needs to be loaded in one shot - use predictions:

  • Let the ORM stuff be lazy
  • customize special requests if necessary
+3


source


To answer your question shortly: I would recommend that you use lazy loading, but you should design your application with lazy loading.

More detailed answer: Lazy loading is the default in NHibernate. So if you don't do anything to get around this, you will be using lazy loading.

With lazy loading, you can use nested objects (with many relationships with other tables) and it will work just fine. They are loaded from the database as needed.

This can lead to some problems - the most famous is the n + 1 problem. Ayende Rahien discussed it here: http://ayende.com/blog/3732/solving-the-select-n-1-problem



These problems can be worked around if you declare what the object should look like, or with smarter queries - but you have to keep this in mind.

Another possible mistake is that you cannot lazy load the object if the session is already closed. It depends a lot on the type of application you are programming and how you use your objects. We had a rich client application with a lot of nested objects and it took us a while to handle the session correctly, but it worked nicely in the end.

Ayende Rahien explains some of the reasons NHibernate uses lazy loading in this post: http://ayende.com/blog/4573/nhibernate-is-lazy-just-live-with-it

This might give you some pointers to learn more about NHibernate and how to safely use lazy loading.

+1


source







All Articles