如何缓存此类查询的结果:
Session.Query<Entity>().Count(e=> e.Property == someConstant)
我不能在它之后放置Cacheable()
,如果我把它放在Count()之前,它会获取整个结果集,不是吗?
答案 0 :(得分:2)
在计数之前添加Cacheable将导致汇总计数结果被缓存。从下面的示例生成的SQL可以看出这一点。
域名和映射代码
public class Entity
{
public virtual long id { get; set; }
public virtual string name { get; set; }
}
public class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
Id(x => x.id).GeneratedBy.Identity();
Map(x => x.name);
Cache.ReadOnly();
}
}
测试代码本身。
using (var session = NHibernateHelper.OpenSession())
using (var tx = session.BeginTransaction())
{
session.Save(new Entity() { name = "Smith" });
session.Save(new Entity() { name = "Smithers" });
session.Save(new Entity() { name = "Smithery" });
session.Save(new Entity() { name = "Smith" });
tx.Commit();
}
String name_constant = "Smith";
using (var session = NHibernateHelper.OpenSession())
using (var tx = session.BeginTransaction())
{
var result = session.Query<Entity>().Cacheable().Count(e => e.name == name_constant);
}
using (var session = NHibernateHelper.OpenSession())
using (var tx = session.BeginTransaction())
{
var result = session.Query<Entity>().Cacheable().Count(e => e.name == name_constant);
}
从上面的代码生成的SQL可以在下面看到。如您所见,有四个INSERT
语句,每个session.Save
一个。尽管存在两个查询,但只有一个SELECT
,而每个查询都在单独的会话下执行。这是因为计数的结果已被NHibernate缓存。
NHibernate: INSERT INTO [Entity] (name) VALUES (@p0); select SCOPE_IDENTITY();
@p0 = 'Smith' [Type: String (4000)]
NHibernate: INSERT INTO [Entity] (name) VALUES (@p0); select SCOPE_IDENTITY();
@p0 = 'Smithers' [Type: String (4000)]
NHibernate: INSERT INTO [Entity] (name) VALUES (@p0); select SCOPE_IDENTITY();
@p0 = 'Smithery' [Type: String (4000)]
NHibernate: INSERT INTO [Entity] (name) VALUES (@p0); select SCOPE_IDENTITY();
@p0 = 'Smith' [Type: String (4000)]
NHibernate: select cast(count(*) as INT) as col_0_0_ from [Entity] entity0_
where entity0_.name=@p0;
@p0 = 'Smith' [Type: String (4000)]
导致NHibernate忽略Cacheable
并返回数据库的可能情况是:
我知道的唯一其他方案将导致NHibernate执行两个SELECT
查询,这是当实体已从缓存中逐出时,显式使用sessionFactory.Evict
或缓存实体之间过期这两个电话。