6

We use NHibernate 4 in our asp.net mvc 4 (.net 4) application. As far as I can tell the behaviour of NHibernate 4 has changed a bit when it comes to second level caching.

The following behaviour seems to have changed (please correct me if I am wrong):

  • There is no longer a transaction needed when using second level cache
  • When I execute a query like (Hibsession.Query().Where(x => x.Name == "x").ToList()), then it will query for the entiry entity. In earlier versions of NHibernate - if i remeber correctly - only the id's of the entity would have been retrieved.

It seems to me that second level only applies in the following cases:

using (var hibSession = SessionFactory.OpenSession())
{
    // Second level cache working
    var entity = hibSession.Get<ChachedEntity>(7);  // second level cache working
    var parent = entity.ParentElement; // second level cache working because n:1

    // Probably working (not tested) 
    var elements = hibSession.Query<ChachedEntity>().Cacheable().Take(30).ToList(); // guessed behaviour: query-cache selects id's and then then uses second level cache

    // second level cache NOT Working
    var children = entity.ChildCollectionWithCachableEntities; // second level cache NOT working because 1:n (!!)
}

My questions are now:

  • Where is the behaviour of the NHibernate 4 second level cache described (or at least changes to version 3 documented)
  • Is it possible to use the second level cache for lazy loading child elements? (or at least ensure that only the id's are loaded and then have the second level cache materialize the entities)

Thanks in advance

Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
Dan Stan
  • 61
  • 1

1 Answers1

0

Transactions are still needed. Failing to use them will disable the cache as soon as you starts updating some cached entities. (See here as for why, I got bitten recently with latest NH version. Why have I overlooked transaction? No excuse... Having moreover read committed snapshot enabled in SQL Server which eliminates deadlocks involving read-only read-committed queries.)

Collection caching works, but must be configured in collection mapping. Add a <cache usage="..." /> node to your sets and other collections needing to be cached. Their contained entities have to be cacheable too for this to be actually useful. (Collection caching only caches related entities primary keys.)

On your querying mechanism loading only ids from DB if the query is cacheable, I have never witnessed that, though I am a long-time user of NHibernate. (I am using it since its 0.9 version, it was already very mature and features rich.) As far as I know, there have not been any serious changes in the second level cache with NH 4. You may check their issues and changes tracker.

Frédéric
  • 9,364
  • 3
  • 62
  • 112