NHibernate query cache makes one request per row to fetch entities

自古美人都是妖i 提交于 2019-12-11 07:42:15

问题


I'm trying out the second level cache in NHibernate. With this code:

return session.Query<Payment>()
    .Cacheable()
    .OrderByDescending(payment => payment.Created)
    .Skip((page - 1)*pageSize)
    .Take(pageSize).ToArray();

If the entities are not in the cache, it will lead to queries like these being executed:

select ... from Payment where Id = 1
select ... from Payment where Id = 2
select ... from Payment where Id = 3

If 100 rows are returned, 100 of these would be executed. I.e. a big performance issue. It would be better if just this query was executed:

select ... from Payment where Id in (1,2,3)

That the entities doesn't exist in the cache can be because of no entity cache configured, limited size of the caches or that the entities in the cache has been expired or removed from the cache.

To not be forced to rely 100% on the entity-cache, is it possible to change the way NHibernate queries for that "missing" entity data?


回答1:


1)Is it possible to configure NHibernate (I use FluentNHibernate with automapping) to also cache the entities?

Yes it is possible to configure Nhibernate second level cache to cache entities. Refer Here

2)And to not be forced to rely 100% on the cache, is it possible to change the way NHibernate queries for that "missing" entity data?

Did you enable "cache.use_query_cache" property in the config file?




回答2:


You need to specify the same cache region in order to "activate" the same caching rules for collections as the main entity. Otherwise it will only cache the main entity, and fetch the collection again if the main entity was loaded from 2nd level cache.

I don't know if this is supported with FluentNhibernate though, you will need to check the docs.

It looks like Collections (Bag) has support for .Cache(CacheMapping mapping)

http://fluentnhibernate.org/api/FluentNHibernate.MappingModel/CacheMapping.htm



来源:https://stackoverflow.com/questions/5801239/nhibernate-query-cache-makes-one-request-per-row-to-fetch-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!