2016-08-25 96 views
2

我理解這個問題已經被問了很多時間,但最不能解釋我的問題:休眠 - 無法獲得交易同步會話當前線程的

@RequestMapping("/testing") 
public String testing(HttpServletRequest request, final ModelMap model) 
{ 
    Transaction ut = session.openSession().beginTransaction(); 

    session.getCurrentSession(); // error here 

    ut.commit(); 

    return "testing"; 
} 

爲什麼我收到錯誤

Could not obtain transaction-synchronized Session for current thread. 

如果我用@Transactional註解方法,它工作得很好。因爲我在我的春天環境中有@EnableTransactionManagement

我想嘗試一下來了解getCurrentSessionopenSession之間的區別,所以我在上面創建了測試用例。

getCurrentSession在活動事務上下文中調用,爲什麼它仍然拋出錯誤???

請參閱this中的代碼。

回答

0

OK,研究這麼長的時間後,我發現我已經錯過下面的paragraph

你不會看到這些代碼片段在一個普通的應用程序;致命的 (系統)例外應始終在「頂部」被捕獲。在其他 單詞中,執行Hibernate的代碼在持久層 層中調用,處理RuntimeException的代碼(通常可以只有 只能清理和退出)位於不同的層中。 Hibernate管理的當前上下文可以通過 訪問SessionFactory來顯着簡化此設計。異常處理將在本章後面的 中討論。

因此,我們確實有展示的例子不會在常規方案工作...

我有如下事情:

// BMT idiom with getCurrentSession() 
try { 
    UserTransaction tx = (UserTransaction)new InitialContext() 
          .lookup("java:comp/UserTransaction"); 

    tx.begin(); 

    // Do some work on Session bound to transaction 
    factory.getCurrentSession().load(...); 
    factory.getCurrentSession().persist(...); 

    tx.commit(); 
} 
catch (RuntimeException e) { 
    tx.rollback(); 
    throw e; // or display error message 
} 

這意味着,中getCurrentSession的使用是相當受限它必須在active(和特定)事務中運行。

相關問題