2011-08-31 60 views
3

我对NHibernate的相对较新的,我有 问题缓存的实体在会话(一级缓存),这里是我的代码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方法,访问数据库不管是什么?谢谢

+1

为您的问题的答案见[这个问题] [1]。 也,我注意到你创建'ISessionFactory'时似乎只创建一个新的会话。应该创建会话,而不是每个应用程序运行时。 [1]:http://stackoverflow.com/questions/4919636/can-first-level-cache-be-used-with-icriteria-or-other-apis –

回答

4

NHibernate不会使用第一级缓存,当你通过除ID以外的东西查询。换句话说,Gets和Loads会查看第一级缓存,但通过Name进行的ICriteria搜索将进入数据库。您可以使用2nd level NHibernate cache或实施您自己的缓存。

作为一个侧面说明,你似乎也有这行的竞争条件:

if (_sessionFactory == null) 

多个线程可以潜在地看到_sessionFactory为空,然后继续进行二次创建。

+1

+1对比赛条件。这让我拧了几次。 '懒惰'来救援!包括双重检查锁定! – Jeff