我在DAO中的用户Session session=SessionFactory.getCurrentSssion()
方法作为我的Struts2应用程序中的类级变量。我在struts拦截器类中维护Transaction。在may DAO类中,当我尝试从DataBase获取数据时,我得到了#34;会话关闭"例外。在我的saveOrUpdate()
方法的代码中,我处理Hibernate Exception。在catch块中,我回滚了Transaction。
请帮助我,如果我使用getCurrentSession()
方法回滚事务时会发生什么。
答案 0 :(得分:2)
您正在使用Hibernate的SessionFactory.getCurrentSession(),它用于创建新会话& 由Hibernate自动管理。这意味着当您调用getCurrentSession()时,Hibernate将此会话与本地线程绑定,如果您在hibernate.cfg.xml文件中设置 hibernate.current_session_context_class 属性,则可以在任何地方访问该线程 。此属性将当前会话绑定到本地线程。
Since, you are using getCurrentSession() method instead of openSession(), your session
will closed automatically by Hibernate as soon you perform any operation on database &
commit the transaction.
例如,
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Student student = new Student();
...
session.save(student);
transaction.commit();
要从此错误中恢复,您应该创建会话作为&在需要时使用sessionFactory.openSession()方法。 通过执行此操作,您可以完全控制会话对象。
如,
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
// do something
transaction.commit();
} catch (Exception ex) {
// on error, revert changes made on DB
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
更多信息:
回滚交易会发生什么?
When you call rollback() method of Transaction it will revert all current changes done
on database. It doesn't have any concern with closing Hibernate session.
答案 1 :(得分:0)
我在struts拦截器类中维护Transaction。 [...]有时我 我正在关闭会议"例外
拦截器不是线程安全的。您可能在拦截器中做错了(在您发布一些代码之前无法确定)。
确保您没有在Class级别使用任何对象,因为它们是线程不安全的。
有关实际示例,请参阅this question。