【问题标题】:How to skip second level cache in query?如何在查询中跳过二级缓存?
【发布时间】:2012-09-17 09:46:53
【问题描述】:

我对一个对象使用实体缓存(二级缓存)。现在,在一个特定的查询(我使用 OueryOver)中,我需要避开二级缓存。我试图在我的查询中省略“Cacheable”属性,但查询仍然被缓存,通过我假设的二级缓存。

我的运行时:

.NET 4.0 NHibernate:3.1.0.4000 流畅的 NHiberante:1.2.0.712

我的对象:

[Serializable]
public class ArticleWishListItem : EntityBase<int>
{
    public virtual int CustomerId { get; set; }
    public virtual int ArticleId { get; set; }
    public virtual DateTime CreatedDate { get; set;  }
}

我的映射:

public class ArticleWishListItemMapping : ClassMap<ArticleWishListItem>
{
    public ArticleWishListItemMapping()
    {
        Cache.ReadWrite().Region("WishList");

        Id(a => a.Id).GeneratedBy.Native();

        Map(a => a.ArticleId).Not.Nullable();
        Map(a => a.CreatedDate).Not.Nullable();
        Map(a => a.CustomerId).Not.Nullable();
    }
}

我的查询结果与我的愿望相反:

    private static List<ArticleWishListItem> GetArticleWishListItemsImplementation(NHibernate.ISession session, int customerId)
    {
        return session.QueryOver<ArticleWishListItem>()
                                       .Where(a => a.CustomerId == customerId)
                                       .List<ArticleWishListItem>()
                                       .ToList<ArticleWishListItem>();
    }

即使我想为实体启用缓存,让这个查询每次都访问数据库的最佳方法是什么?我可以使用 IStatelessSession,它会在这种情况下工作,因为它会跳过二级缓存,但这是推荐的解决方案吗?

【问题讨论】:

    标签: nhibernate fluent-nhibernate


    【解决方案1】:

    你需要使用 CacheMode.Ignore(只会在更新发生时使缓存失效),CacheMode.Refresh(将刷新缓存中的所有项目并忽略 use_minimal_puts)或 CacheMode.Put(将刷新任何在缓存中无效的项目)我认为的缓存)。枚举值上的 cmets 告诉您它们做得更好。

    例如:

    return session.QueryOver<ArticleWishListItem>()
        .Where(a => a.CustomerId == customerId)
        .CacheMode(CacheMode.Refresh)
        .List<ArticleWishListItem>();
    

    我不确定你为什么再次调用 .ToList - 这对我来说似乎是多余的,因为对 .List 的调用将返回一个列表......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-28
      • 2011-12-18
      • 2014-06-20
      • 2014-05-28
      • 1970-01-01
      • 2011-02-19
      • 2014-06-28
      • 2015-10-23
      相关资源
      最近更新 更多