2011-08-31 3 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가 아닌 다른 것으로 쿼리 할 때 첫 번째 레벨 캐시를 사용하지 않습니다. 즉, 가져 오기 및로드는 첫 번째 수준의 캐시를 조사하지만 이름으로 검색하는 ICriteria는 데이터베이스로 이동합니다. 2nd level NHibernate cache을 사용하거나 자체 캐싱을 구현할 수 있습니다.

if (_sessionFactory == null) 

다중 스레드가 잠재적으로 널 _sessionFactory보고 두 번을 만들 진행할 수 : 측면으로

당신이이 줄에서 경쟁 조건을 갖고있는 것 같다 있습니다.

+1

+1 경쟁 조건. 이것은 몇 번 나를 망쳤다. '게으른 '를 구하십시오! 더블 체크 잠금 장치가 포함되어 있습니다! – Jeff