我在问我应该如何处理后台线程在我的Hibernate/Spring Web应用程序中执行涉及数据库的任务。如何处理Hibernate/Spring应用程序中的后台线程
目前我正在使用下面的拦截器,所以我可以用@OpenSession注释我的线程运行方法,应该打开一个会话。这也应该适用于RMI请求,例如或者在没有打开会话的情况下调用的任何其他方法。但是,我不确定代码是否正确,我面临的问题是有时会话只是没有关闭并且永远打开。
@Around("@annotation(openSession)")
public Object processAround(ProceedingJoinPoint pjp, OpenSession openSession) throws Throwable {
boolean boundResource = false;
Session session = null;
// Bind the session to the thread, if not already done
if(TransactionSynchronizationManager.getResource(sessionFactory) == null) {
log.debug("Opening Hibernate Session in method "+pjp.getSignature());
session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
boundResource = true;
}
// Invoke the annotated method
Object ret;
try {
ret = pjp.proceed();
}
catch(Throwable t) {
// Rethrows the Exception but makes sure the session will be closed
SessionFactoryUtils.closeSession(session);
log.debug("Closing Hibernate Session in method (Exception thrown) "+pjp.getSignature());
throw t;
}
// If a resourc was bound by this method call, unbind it.
if(boundResource) {
//SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
session.flush();
SessionFactoryUtils.closeSession(session);
log.debug("Closing Hibernate Session in method "+pjp.getSignature());
}
return ret;
}
你为什么需要它?你不能只使用'@ Transactional'吗? – axtavt 2011-06-16 16:53:54
这会为我打开一个会话吗?如果会话已经存在会发生什么? – Erik 2011-06-16 16:56:52
据我了解,它基本上与你的代码完全一样。 – axtavt 2011-06-16 17:06:02