我正在尝试 NHibernate 中的二级缓存。使用以下代码:
return session.Query<Payment>()
.Cacheable()
.OrderByDescending(payment => payment.Created)
.Skip((page - 1)*pageSize)
.Take(pageSize).ToArray();
如果实体不在缓存中,则会导致执行类似以下的查询:
select ... from Payment where Id = 1
select ... from Payment where Id = 2
select ... from Payment where Id = 3
如果返回 100 行,则将执行其中的 100 行。即一个很大的性能问题。如果只执行此查询会更好:
select ... from Payment where Id in (1,2,3)
缓存中不存在实体可能是因为没有配置实体缓存、缓存大小有限或者缓存中的实体已过期或从缓存中删除。
为了不被迫 100% 依赖实体缓存,是否可以更改 NHibernate 查询“丢失”实体数据的方式?
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?
发布评论
评论(2)
1)是否可以配置NHibernate(我使用具有自动映射功能的FluentNHibernate)来缓存实体?
是的,可以配置 Nhibernate 二级缓存来缓存实体。
请参阅此处
2)并且不要被迫 100% 依赖缓存,是否可以改变 NHibernate 查询“丢失”实体数据的方式?
您是否在配置文件中启用了“cache.use_query_cache”属性?
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?
您需要指定相同的缓存区域,以便为集合“激活”与主实体相同的缓存规则。否则,它只会缓存主实体,如果主实体是从二级缓存加载的,则再次获取集合。
我不知道 FluentNhibernate 是否支持这一点,您需要检查文档。
看起来 Collections (Bag) 支持 .Cache(CacheMapping 映射)
http://fluentnhibernate .org/api/FluentNHibernate.MappingModel/CacheMapping.htm
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