score:2

Accepted answer

adding cacheable before the count will cause the aggregate count results to be cached. this can be seen by the sql generated from my example below.

domain and mapping code

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();
    }
}

the test code itself.

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);
}

the sql generated from the above code can be seen below. as you can see, there are four insert statements, one for each session.save. whereas there is only one select despite the two queries, each performing under a separate session. this is because the result of the count has been cached by 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)]

the possible scenarios which will cause nhibernate to ignore cacheable and go back to the db are when:

  1. the second level cache is not enabled in the session factory configuration.
  2. the entity has not been marked as cacheable.

the only other scenario i know of that will cause nhibernate to perform two select queries is when the entity has been evicted from the cache, either explicitly using sessionfactory.evict or by the cached entity becoming expired between the two calls.


Related Query

More Query from same tag