I ask how I can work with background threads performing database related tasks in my Hibernate / Spring web application.
I am currently using the following interceptor, so I can annotate the methods of starting a thread using @OpenSession, and the session should be open. This should also work for RMI requests, for example, or any other method that is called without opening a session. However, I'm not sure if the code is correct, I am faced with the problem that sometimes sessions are simply not closed and remain open forever.
@Around("@annotation(openSession)")
public Object processAround(ProceedingJoinPoint pjp, OpenSession openSession) throws Throwable {
boolean boundResource = false;
Session session = null;
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;
}
Object ret;
try {
ret = pjp.proceed();
}
catch(Throwable t) {
SessionFactoryUtils.closeSession(session);
log.debug("Closing Hibernate Session in method (Exception thrown) "+pjp.getSignature());
throw t;
}
if(boundResource) {
session.flush();
SessionFactoryUtils.closeSession(session);
log.debug("Closing Hibernate Session in method "+pjp.getSignature());
}
return ret;
}
source
share