2013-10-10 29 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,代码工作正常。 –