NHibernate does not find named query result sets in second level cache

I have a simple unit test where I run the same NHibernate named query 2 times (each time each time) with the same parameter. This is a simple int parameter, and since my query is a named query, I assume that these 2 calls are identical and the results should be cached.

In fact, I can see in my journal that the ARE results are cached, but with different keys. So, my 2nd query results were never found in the cache.

here is a snippet from my log (note how different keys are):

(first request)

DEBUG NHibernate.Caches.SysCache2.SysCacheRegion [(null)] & ​​lt; (null)> - adding new data: key = [snipped] ... parameters: ['809']; named parameters: {} @ 743460424 & value = System.Collections.Generic.List`1 [System.Object]

(second request)

DEBUG NHibernate.Caches.SysCache2.SysCacheRegion [(null)] & ​​lt; (null)> - adding new data: key = [snipped] ... parameters: ['809']; named parameters: {} @ 704749285 & value = System.Collections.Generic.List`1 [System.Object]

I have NHibernate configured to use the query cache. And I have these requests set as cacheable = true. I don’t know where else to look. Anyone have any suggestions?

thanks
-Mike

+4
source share
1 answer

Ok, I figured it out. I ran my named query using the following syntax:

IQuery q = session.GetNamedQuery("MyQuery") .SetResultTransformer(Transformers.AliasToBean(typeof(MyDTO))) .SetCacheable(true) .SetCacheRegion("MyCacheRegion"); 

(which, I could add, EXACTLY how NHibernate tells you how to do it .. but I get distracted;))

If you use the creation of a new AliasToBean Transformer for each request, each request object (which is the key to the cache) will be unique and you will never get a cache hit. So, in short, if you do this, as nhib docs say, then caching will not work.

Instead, create your transformer once in the static var element, and then use it for your request, and caching will work - for example:

 private static IResultTransformer myTransformer = Transformers.AliasToBean(typeof(MyDTO)) 

...

 IQuery q = session.GetNamedQuery("MyQuery") .SetResultTransformer(myTransformer) .SetCacheable(true) .SetCacheRegion("MyCacheRegion"); 
+2
source

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


All Articles