NHibernate 4: using a second level cache for lazy loading

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

Perhaps the following behavior has changed (please correct me if I am wrong):

  • No more transaction when using a second level cache
  • When I execute a query like (Hibsession.Query (). Where (x => x.Name == "x"). ToList ()), then it will request an entiry object. In earlier versions of NHibernate - if I remember correctly - only the object identifier would be retrieved.

It seems to me that the second level applies only 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 and then then uses second level cache // second level cache NOT Working var children = entity.ChildCollectionWithCachableEntities; // second level cache NOT working because 1:n (!!) } 

Now my questions are:

  • Where the behavior of NHibernate 4 second-level cache is described (or at least version 3 changes have been made)
  • Is it possible to use second level cache for lazy boot children? (or at least make sure that only the identifier is loaded, and then materialize the second-level entities).

Thank you in advance

+6
source share
1 answer

Transactions are still needed. If you do not use them, you will turn off the cache as soon as you start updating some cached objects. ( Look here why , I recently bit the latest version of NH. Why did I forget the transaction? No excuses ... Also, read committed snapshot included in SQL Server, which removes deadlocks related to read-only read requests.)

Collection caching works, but must be configured in collection mapping. Add the <cache usage="..." /> node to your collections and other collections that need to be cached. Their contained objects must be cacheable in order to be truly useful. (Collection caching only caches the associated primary keys of related objects.)

In your query engine, only identifiers from the database are loaded, if the request is cached, I have never witnessed this, although I am a long-time user of NHibernate. (I have been using it since version 0.9, it was already very mature and rich.) To my knowledge, there were no major changes in the second level cache with NH 4. You can check their problems and changes> .

0
source

Source: https://habr.com/ru/post/979775/


All Articles