NHibernate session 不缓存

标签 nhibernate

我是 Nhibernate 的新手,我在缓存 session 中的实体时遇到问题(一级缓存) 这是我的代码

public Book IProductRepository.GetBookbyName(string bookName)
{
        ISession session = NHibernateHelper.GetSession();
        ICriteria criteria = session.CreateCriteria<Book>()
                                     .Add(Restrictions.Eq("Name", bookName));
        return criteria.UniqueResult<Book>();
}

私有(private)静态ISessionFactory _sessionFactory;

    private static ISessionFactory SessionFactory
    {
        get
        {
            if (_sessionFactory == null)
            {
                var configuration = new Configuration();
                configuration.Configure();
                configuration.AddAssembly(typeof(Product).Assembly);
                _sessionFactory = configuration.BuildSessionFactory();
                CurrentSessionContext.Bind(_sessionFactory.OpenSession());
            }
            return _sessionFactory;
        }
    }


    public static ISession GetSession()
    {
        return SessionFactory.GetCurrentSession();
    }

配置文件是

<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Server=(local);initial catalog=NhibernateTest;Integrated Security=SSPI</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<property name ="current_session_context_class">thread_static</property>
<property name="cache.use_query_cache" >true</property>
<property name="show_sql">true</property>

而且每次我调用 GetBookByName 方法时,它无论如何都会访问数据库?谢谢

最佳答案

当您通过 Id 以外的其他内容进行查询时,NHibernate 将不会使用一级缓存。换句话说,Gets 和 Loads 会查找一级缓存,而 ICriteria 按 Name 查找会查找数据库。您可以使用 2nd level NHibernate cache或者实现你自己的缓存。

作为旁注,您似乎在这一行也有竞争条件:

if (_sessionFactory == null)

多个线程可能会将 _sessionFactory 视为 null 并继续创建它两次。

关于NHibernate session 不缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262794/

相关文章:

NHibernate 映射按代码级联 All-Delete-Orphans

c# - Azure 上的 NHibernate?

c# - 错误 : 22001: value too long for type character varying(255)

c# - 在查询中生成错误的列

oracle - 如何使用 NHibernate 以编程方式调用 Oracle 存储过程?

nhibernate - Ninject 会调用 dispose 并关闭 NHibernate Isession 吗?

c# - 流利的休眠状态 : Enum in composite key gets mapped to int when I need string

NHibernate 双向一对一映射问题

c# - 流利的 NHibernate,实现 ISQLExceptionConverter 的正确方法

NHibernate AliasToBeanResultTransformer 和集合