2013-10-10 70 views
0

這是從休眠約批處理代碼示例:爲什麼在休眠批處理使用的openSession()

Session session = sessionFactory.openSession(); 
Transaction tx = session.beginTransaction(); 

for (int i=0; i<100000; i++) { 
    Customer customer = new Customer(.....); 
    session.save(customer); 
    if (i % 20 == 0) { //20, same as the JDBC batch size 
     //flush a batch of inserts and release memory: 
     session.flush(); 
     session.clear(); 
    } 
} 

tx.commit(); 
session.close(); 

在代碼的開始,它使用openSession()。但是,當我寫我的代碼,我使用getCurreentSession()。它似乎會產生org.hibernate.TransactionException: nested transactions not supported錯誤。

有人能解釋爲什麼會發生這種情況嗎?

回答

0

SessionFactory.openSession()總是會打開一個新的會話,您必須在完成操作後關閉該會話。 SessionFactory.getCurrentSession()返回一個綁定到上下文的會話 - 你不需要關閉它。

+0

感謝您的回覆。我的主要問題是,爲什麼當我使用getCurrentSession()時會產生錯誤。是否由會話在其他地方持有的其他事務引起,因爲會話是綁定到上下文的?順便說一句,一旦我改變了getCurrentSession openSession,代碼工作正常。 –