29

有没有人有一个示例如何设置以及在流畅的 nhibernate 中缓存哪些实体。都使用流利的映射和自动映射?

实体关系也是如此,包括一对多和多对多?

4

1 回答 1

33

我一直在处理类似的情况,我只想缓存特定元素,并希望这些元素在启动时加载一次,并保存在缓存中,直到应用程序关闭。这是一个只读缓存,用于填充国家列表,以便用户可以从列表中选择他们的国家。

我使用了 fluentNhibernate Mappings,并使用 Cache.readonly() 定义了 Country 我的类

public class CountryMap : ClassMap<Country> {
    public CountryMap() { 
         Schema("Dropdowns");
         Cache.ReadOnly();
         // Class mappings underneath 
    }
}

我的用户类映射如下所示:

public class UserMap : ClassMap<User> {
    Id(x => x.Id).Column("UserId");
    Map(x => x.FirstName);
    Map(x => x.LastName);
    References(x => x.Country)
      .Column("CountryId");
}

我手动配置 Fluent Nhibernate 以使用二级缓存。所以在我流利的配置中,我有:

var sessionFactory = Fluently.Configure()
    .Database (...) // set up db here
    .Mappings(...)  //set up mapping here
    .ExposeConfiguration(c => {
        // People advice not to use NHibernate.Cache.HashtableCacheProvider for production
        c.SetProperty("cache.provider_class", "NHibernate.Cache.HashtableCacheProvider");
        c.SetProperty("cache.use_second_level_cache", "true");
        c.SetProperty("cache.use_query_cache", "true");
    })
    .BuildSessionFactory();

我已经检查了 SQL 探查器,当我得到一个用户的国家列表时,它们被加载一次,并且在每个其他请求之后我都会得到缓存命中。好消息是当显示用户的国家名称时,它从缓存中加载,而不向数据库发出请求。我从Gabriel Schenker的这篇文章中得到了一些提示。希望有帮助吗?如果您找到更好/正确的方法,请告诉我?谢谢!

于 2009-11-24T11:50:17.733 回答