NHibernate Lazy Loading - NHibernate

What is NHibernate Lazy Loading?

In this section, we will be discussing the lazy loading feature. It is a completely different idea by default and NHibernate doesn't have lazy loading, for instance if you load a customer, it's not going to load all of the orders.

  • The order collection will be loaded on demand.
  • Any connotation, whether it is a many-to-one or a collection is lazy loaded by default, it requires an Open ISession.
  • If you have shut your session, or if you have committed your transaction, you can get a lazy load exception that it cannot pull in those additional objects.
  • You have to be careful about lazy loading and how much data you actually need.
  • You can turn off lazy loading for an entire association or you could put lazy equals false or you can also specify a fetching strategy.

Here is the Program.cs file implementation.

To appreciate this, let's run the application and take a look at the NHibernate Profiler.

As you can see that we have the Select From Customer, given a particular customer ID and then we also have another Select From Orders table, when it actually accesses that customer's collection.

So we have 2 roundtrips to the database. Now, sometimes, we would want to optimize this. To do this, let’s go to the customer.hbm.xml file and add a fetching strategy and ask it to do a join fetch.

As you can realize that we haven't altered any code in our application, we have impartialy added a fetching strategy in the customer.hbm.xml. Let’s run this application again, it still behaves exactly the same way. Let's look at NHibernate Profiler.

Earlier, program had two round trips to the database, currently, it only has one and that's since it's doing a left outer join here.
We can get that it's doing a left outer join between the customer table and the order table based on the customer ID, and therefore, it's able to load in all of that information at once.

We have saved 1 roundtrip to the database.

The down side is that the customer information will be replicated on both lines and that's the way that a SQL left outer join works.
So with the fetching strategy, we are pulling back a bit more data and we are saving a roundtrip.

You can also do this at the query level, so let's go to the Program.cs file and look at the simpler reloaded example.

Here, we are doing a load by the customer. Now let’s change it to a query and we will use a link query as shown in the following code.

Let’s also remove the fetching strategy from the customer.hbm.xml file.

Let’s run this application again and you will see the following output.

Currently let’s look at the NHibernate Profiler, you can see that we've got this eager join fetch happening once again, but this time, it's based on the query.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

NHibernate Topics