NHibernate 4:二级缓存用于延迟加载子集合

Dan*_*tan 6 nhibernate second-level-cache

我们在asp.net mvc 4(.net 4)应用程序中使用NHibernate 4.据我所知,NHibernate 4的行为在二级缓存方面有所改变.

以下行为似乎已经改变(如果我错了,请纠正我):

  • 使用二级缓存时不再需要事务
  • 当我执行像(Hibsession.Query().Where(x => x.Name =="x").ToList())这样的查询时,它将查询entiry实体.在早期版本的NHibernate中 - 如果我记得正确 - 只会检索实体的id.

在我看来,第二级仅适用于以下情况:

using (var hibSession = SessionFactory.OpenSession())
{
    // Second level cache working
    var entity = hibSession.Get<ChachedEntity>(7);  // second level cache working
    var parent = entity.ParentElement; // second level cache working because n:1

    // Probably working (not tested) 
    var elements = hibSession.Query<ChachedEntity>().Cacheable().Take(30).ToList(); // guessed behaviour: query-cache selects id's and then then uses second level cache

    // second level cache NOT Working
    var children = entity.ChildCollectionWithCachableEntities; // second level cache NOT working because 1:n (!!)
}
Run Code Online (Sandbox Code Playgroud)

我现在的问题是:

  • 所描述的NHibernate 4二级缓存的行为在哪里(或至少记录到版本3的更改)
  • 是否可以使用二级缓存来延迟加载子元素?(或者至少确保只加载id,然后让二级缓存实现实体)

提前致谢

Fré*_*ric 0

仍然需要交易。如果不使用它们,一旦您开始更新某些缓存实体,就会禁用缓存。(请参阅此处了解为什么,我最近被最新的 NH 版本所困扰。为什么我忽略了事务?没有借口...此外read committed snapshot在 SQL Server 中启用了它,消除了涉及只读、已提交查询的死锁。)

Collection caching works, but must be configured in collection mapping. Add a <cache usage="..." /> node to your sets and other collections needing to be cached. Their contained entities have to be cacheable too for this to be actually useful. (Collection caching only caches related entities primary keys.)

On your querying mechanism loading only ids from DB if the query is cacheable, I have never witnessed that, though I am a long-time user of NHibernate. (I am using it since its 0.9 version, it was already very mature and features rich.) As far as I know, there have not been any serious changes in the second level cache with NH 4. You may check their issues and changes tracker.