Search code examples
cachingnhibernatefluent-nhibernatesecond-level-cache

NHibernate Second Level Cache not caching results from Query Cache


In our application configuration, we've got NHibernate configured with both second level and query caches enabled with the SysCacheProvider, configured Fluently...

.Cache(x => x.UseQueryCache().ProviderClass<SysCacheProvider>().UseSecondLevelCache())

We have an entity called Lookup that is marked with Cache.ReadOnly() in its mapping file, and we fetch it using CreateCriteria with SetCacheable(true).SetCacheMode(CacheMode.Normal).

The problem is that the second level cache doesn't seem to be used. Using NHProf, we can see that the first query to fetch the Lookup (by a unique string ID) is correctly cached, but on every call NHibernate then goes to the database to fetch the row by the cached sql ID, rather than using the second level cache.

I've done everything in this blog but to no avail.

Is there something else I need to do, or are there any pitfalls that can mean that entities don't get added to the second level cache?


Solution

  • Are you using transactions?

    If answer is no, give up second level cache, or start using transactions. For ensuring it caches only valid data, the cache kind of disables itself if data is modified without using a transaction.

    See the documentation:

    The second level cache requires the use of transactions, be it through transaction scopes or NHibernate transactions. Interacting with the data store without an explicit transaction is discouraged, and will not allow the second level cache to work as intended.

    It is a common pitfall, trying to use the cache without using transactions, as here. This confirms it too. Another reason could be this one, more tricky.