tags:

views:

35

answers:

1

Hi All

I am working in a project that's work with N Hibernate. Due to performance issues and increasing in complexity of the project we need to do association manually in our code.As we all know for that we have to set lazy property true. What i want know that, is their any way to do association with set lazy property true.We have already created our own methods for filling Association.But still for that also we need to write much quries and code which is not satisfactory.

Please let me know some way for this. Thanks.

+4  A: 

Lazy loading is turned on by default. There is basically two ways how lazy loading is implemented by NHibernate.

  1. Lazy loading of collections
  2. Lazy loading of "single ended" references (many-to-one)

Collections are easy and straight forward. NHibernate uses its own implementation if the collection classes anyway, lazy loading is implemented there.

Single ended references ("normal" associations) are not that easy. Lazy loading is implemented in a proxy. The proxy is a class created at runtime which inherits from the referenced class. That's why everything in the referenced class needs to be virtual. The proxy overrides every member and makes sure that the data is loaded when a member is accessed from outside. The problem with the proxy is, if you reference a base class, you get a proxy from the base class and you can't downcast it to the real class. So be careful when using lazy loading with inherited classes.

Lazy is turned on by default, you need to explicitly turn it off. So you don't need to do anything special to get lazy loading.

When you are optimizing performance, also consider to use batch-fetching.

for single ended associations:

<class name="xx" batch-size="10"> 

and on collections:

<bag name="xx" .... batch-size="10">

it reduces the N+1 problem a lot (by factor of 10 in this example.).

Stefan Steinegger
Stefan can u please let me know the purpose of batch-size? how it can help?
Amit
batch-size lets NHibernate "prefetch" data. Let's say you have class `A` referencing class `B`. You have 200 `A`s loaded from database. When you access the first `B`, it loads not only this single `B` instance. This would generate 200 queries for `B`s. It loads 10 `B`s at once. So it generates only 20 queries.
Stefan Steinegger
Thanks lots for information stefan
Amit