希望得到您的帮助。 我有简单的主孩子集("播放器"和#34; playerChildObject")。获取"球员"还会抓住他们相关联的孩子。
SysCache会缓存玩家,但不会缓存儿童。
以下是对象(均使用Cache.ReadWrite()设置):
实体:
public class Player
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<PlayerChildObject> PlayerChildObjects { get; set; }
public Player()
{
PlayerChildObjects = new List<PlayerChildObject>();
}
}
public class PlayerChildObject
{
public virtual int Id { get; protected set; }
public virtual Player Player { get; set; }
}
映射:
public class PlayerMap : ClassMap<Player>
{
public PlayerMap()
{
Id(x => x.Id).Column("id");
Map(x => x.Name).Column("name");
HasMany(x => x.PlayerChildObjects).KeyColumn("PlayerId")
.Inverse()
.Cascade.All()
.Not.LazyLoad();
Table("accounts");
Cache.ReadWrite();
}
}
public class PlayerChildObjectMap : ClassMap<PlayerChildObject>
{
public PlayerChildObjectMap()
{
Id(x => x.Id).Column("id");
References<Player>(x => x.Player, "playerId");
Table("playerChildObjects");
Cache.ReadWrite();
}
}
会话工厂还使用&#34; UseQueryCache&#34;和&#34; UseSecondLevelCache&#34;:
Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(cs => ...))
.Cache(c => c.UseQueryCache().UseSecondLevelCache()
.ProviderClass(typeof (NHibernate.Caches.SysCache.SysCacheProvider).AssemblyQualifiedName))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<PlayerChildObjectMap>())
.BuildSessionFactory();
查询本身使用SetCacheable(true).SetCacheMode(CacheMode.Normal):
using (var session = SessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
players = session.CreateCriteria(typeof(Player))
.SetCacheable(true)
.SetCacheMode(CacheMode.Normal)
.List<Player>();
transaction.Commit();
}
}
然而,探查器显示玩家被缓存(仅被称为第一次执行玩家获取代码),而每次由PlayerID检索相同的PlayerChildObjects。
因此,第一个请求提供N + 1个DB调用(每个玩家的玩家列表+子对象),所有连续请求执行N个调用(每个玩家的子对象)。
我错过了什么? 如何让SysCache缓存儿童?
SysCache版本:3.1.0.4000
答案 0 :(得分:2)
我想说,有两个问题。首先,即使 one-to-many
(HasMany
)也有缓存设置:
HasMany(x => x.PlayerChildObjects).KeyColumn("PlayerId")
...
.Cache.IncludeAll() // or .IncludeNonLazy, .CustomInclude("customInclude")
.ReadOnly() // or .NonStrictReadWrite(), .ReadWrite(), .Transactional(),
// .CustomUsage("customUsage")
.Region("regionName");
检查更多邻近HasMany mapping here(Adam Bar关于按代码映射的文章,但最后是流利的)
其次,我们应该使用批量获取:
public PlayerMap()
{
BatchSize(25);
HasMany(x => x.PlayerChildObjects).KeyColumn("PlayerId")
...
.BatchSize(25)
...
public PlayerChildObjectMap()
{
BatchSize(25);
...
在doc 19.1.5. Using batch fetching或此处了解更多相关信息: