我正在开发一个网络应用程序。通常在请求开始时(通过架构代码),会打开一个 Hibernate session 来处理 DB 事务。在请求结束时, session 关闭。这对我们所有的交易都非常有效,除了在一个特定的实例中,我想从一个请求中触发一个线程。该线程将调用数据库事务。
在线程中,我调用“sessionFactory.openSession()”,并在这个 session 中执行我的交易。问题在于,当请求完成时,线程本身可能不一定完成。因此,当请求完成并且线程尝试执行另一个数据库事务时,我得到一个 Hibernate Session is Closed!错误。
无论如何,我是否可以从我的线程中打开一个“干净的” session ,与请求开始时打开的 session 无关?
最佳答案
您可以创建一个线程服务,它扩展了 HibernateAccessor
,作为一个独立的 Spring 服务,在 spring.xml
中定义,并向它发送您想要的代码/数据过程。像这样:
Session session = SessionFactoryUtils.getSession(
getSessionFactory(), getEntityInterceptor(), getJdbcExceptionTranslator());
SessionHolder sessionHolder = null;
try {
applyFlushMode(session, false);
sessionHolder = new SessionHolder(session);
TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder);
Transaction t = getSessionFactory().getCurrentSession().beginTransaction();
try {
//execute your code here
t.commit();
} catch (Exception e) {
t.rollback();
log.error("Error", e);
}
try {
flushIfNecessary(sessionHolder.getSession(), false);
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
} finally {
SessionFactoryUtils.closeSession(sessionHolder.getSession());
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
关于java - 为后台线程从 Hibernate 获取新 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337586/