【问题标题】:NHibernate session is not cachingNHibernate 会话没有缓存
【发布时间】:2011-11-07 22:24:17
【问题描述】:

我对 Nhibernate 比较陌生,我在缓存会话中的实体时遇到问题(一级缓存) 这是我的代码

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

私有静态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 方法时,它都会访问数据库吗?谢谢

【问题讨论】:

  • 如需回答您的问题,请参阅 [this question][1]。另外,我注意到您在创建ISessionFactory 时似乎只创建了一次新会话。会话应该按调用创建,而不是按应用程序运行时创建。 [1]:stackoverflow.com/questions/4919636/…

标签: nhibernate


【解决方案1】:

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

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

if (_sessionFactory == null)

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

【讨论】:

  • +1 竞争条件。这搞砸了我几次。 Lazy&lt;T&gt; 救援!包括双重检查锁定!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多