1
votes

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?

2

2 Answers

2
votes

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.

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.

1
votes

The caching fails when we are using NHibernate from within an NServiceBus handler. It turns out that within NSB handlers, the second level cache is not supported for the version we are using (version 5.x).