2011-08-31 100 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