tags:

views:

35

answers:

1

Hi, I am bit new to NHibernate, and I have this question regarding the performance. Say we have two tables, A and B, mapped to classes A and B respectively.

class A {
    int IdA;
    //...
}
class B {
    int IdB;
    public A MyA;
    //...
}

First I load a List<A> from DB, and then load a List<B>. When loading List<B> does it query the DB again to get MyA value, or does NHibernate keep a reference of which As has been loaded already so it reduces duplicate DB access?

Thanks a lot in advance, Anuruddha

+3  A: 

You need to understand how caching works on NHibernate:

First level cache When using NHibernate the first level cache is automatically enabled as long as one uses the standard session object. [...] When NHibernate is loading an entity by its unique id from the database then it is automatically put into the so called identity map. This identity map represents the first level cache. The life-time of the first level cache is coupled to the current session. As soon as the current session is closed the content of the respective first level cache is cleared.

  • In short, within the same session, NHibernate will automatically keep the result from fetched queries in cache and automatically use it in the case than it gets invoked more than once.

Second level cache The life time of the second level cache is tied to the session factory and not to an individual session. Once an entity is loaded by its unique id and the second level cache is active the entity is available for all other sessions (of the same session factory). Thus once the entity is in the second level cache NHibernate won't load the entity from the database until it is removed from the cache.

  • In short, regardless of the session, you can specify which queries you want cached for further operations. By default, NHibernate will keep this cache updated as long as the cached entities are updated via NHibernate (and not an external application).

First and second level caching on NHibernate.

Rafael Belliard
Thanks Rafael, that gave me a good insight into what I really needed to know :)
Anuruddha