【发布时间】:2014-09-11 05:42:50
【问题描述】:
根据Hibernate documentation,Hibernate 抛出异常后使用 Session 是不安全的。
如果 Session 抛出异常,包括任何 SQLException,立即回滚数据库事务,调用 Session.close() 并丢弃 Session 实例。 Session 的某些方法不会使会话保持一致状态。 Hibernate 抛出的任何异常都不能被视为可恢复的。通过在 finally 块中调用 close() 确保 Session 将被关闭。
在我的代码中,我正在执行批量插入。我正在使用sessionFactory.getCurrentSession() 方法来获取会话。我的代码是这样的。
try {
//some code here....
....
Table1Entity table1Entity = .......
List<Table2Entity> table2Entities = .......
Session currentSession = sessionFactory.getCurrentSession();
for (int i = 0; i < table2Entities; i++) {
.............
currentSession.save(table2Entities.get(i));
if(i % batchSize == 0 || i + 1 == table2Entities) {
currentSession.flush();
currentSession.clear();
}
}
} catch (Exception e) {
currentSession.getTransaction().rollback();
//currentSession.close(); //According to documentation Session should be closed here
table1Entity.setError(true);
currentSession.save(table1Entity);//According to documentation Session should not be used here
.......
}
正如文档所说,在引发异常后不应使用会话。我的问题是因为我使用的是currentSession,如何将table1Entity 保存在catch 块中?我应该使用openSession() 方法还是任何其他方式打开一个新会话?
编辑: 更清楚地说,我要问的是我是否可以在现有的 currentSession 关闭后检索新的 currentSession。
【问题讨论】:
-
this 是否在某处为您提供帮助
-
@ankur-singhal 感谢您的链接。但这并不能解决我的问题。在那个答案中,他回滚了整个事务。在我的情况下,我需要在抛出异常后保留另一个实体。
标签: java spring hibernate session bulkinsert