2013-03-01 38 views
4

我正在使用java命令行應用程序測試hibernate 4.1.9。我已經配置了當前會話的上下文線程:hibernate - getCurrentSession - 無活動事務無效

<property name="hibernate.current_session_context_class">thread</property> 

但是,當我調用sessionFactory.getCurrentSession()它拋出一個異常:

Exception in thread "main" org.hibernate.HibernateException: get is not valid without active transaction 
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348) 
    at com.sun.proxy.$Proxy9.get(Unknown Source) 
.... 

我可以用openSession,它不會真正的問題(這是一個畢竟測試)。我只是好奇,爲什麼我不能讓方法getCurrentSession像廣告一樣工作。

謝謝。

回答

2

第一次調用sessionFactory.getCurrentSession()會返回一個新的會話。問題出在我的配置上。

我有這樣的:

<property name="hibernate.current_session_context_class">thread</property> 

將其更改爲在此之後,它的工作:

<property name="current_session_context_class">thread</property> 
+0

你確定這解決了該問題? – hop 2013-03-05 19:42:56

+0

我不認爲這是解決這個問題的方法。 – lephix 2013-06-19 15:18:51

+0

我只是試過這個,它不能解決問題 – catrapture 2013-07-19 04:50:10

0

這是一個有點老問題,但回答是正確的思想。

通過將屬性名稱hibernate.current_session_context_class更改爲current_session_context_class,強制使用默認JTASessionContext

下面的代碼片段來自休眠SessionFactoryImpl。 BTW,Environment.CURRENT_SESSION_CONTEXT_CLASS"hibernate.current_session_context_class"ThreadLocalSessionContext導致此問題。

private CurrentSessionContext buildCurrentSessionContext() { 
     String impl = (String) properties.get(Environment.CURRENT_SESSION_CONTEXT_CLASS); 
     // for backward-compatibility 
     if (impl == null) { 
      if (canAccessTransactionManager()) { 
       impl = "jta"; 
      } 
      else { 
       return null; 
      } 
     } 

     if ("jta".equals(impl)) { 
//   if (! transactionFactory().compatibleWithJtaSynchronization()) { 
//    LOG.autoFlushWillNotWork(); 
//   } 
      return new JTASessionContext(this); 
     } 
     else if ("thread".equals(impl)) { 
      return new ThreadLocalSessionContext(this); 
     } 
     else if ("managed".equals(impl)) { 
      return new ManagedSessionContext(this); 
     } 
     else { 
      try { 
       Class implClass = serviceRegistry.getService(ClassLoaderService.class).classForName(impl); 
       return (CurrentSessionContext) 
         implClass.getConstructor(new Class[] { SessionFactoryImplementor.class }) 
         .newInstance(this); 
      } 
      catch(Throwable t) { 
       LOG.unableToConstructCurrentSessionContext(impl, t); 
       return null; 
      } 
     } 
    } 

請檢查ThreadLocalSessionContext.TransactionProtectionWrapper.invoke

相關問題