Hi there,
for anyone who is interested, here another solution how one can share hibernate objects within http sessions without hibernate exceptions. It should prevent threads from concurring on hibernate objects in http sessions.
The following code could be placed in a Filter responsible for opening and closing hibernate sessions in tomcat apps.
Regards,
Pvblivs
Code:
private void doFilterHibernate(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// before processing filter chain:
// create a hibernate session and open a jdbc connection
// (in some cases, jdbc connections may not be needed:
// switch lazyDatabase to true)
try {
HibernateUtil.getInstance().createSession();
if (!lazyDatabase)
HibernateUtil.getInstance().currentSession();
} catch (DatabaseException e) {
LOG.fatal("Error creating hibernate session", e);
}
try {
// process filter chain
chain.doFilter(request, response);
} finally {
// after processing filter chain:
// close the current hibernate session
// (an underlying jdbc connection will be closed as well
// if it has been opened)
try {
HibernateUtil.getInstance().closeSession();
} catch (DatabaseException e) {
LOG.fatal("Error closing hibernate session", e);
}
}
}
/**
* Processes the filtering for http requests. If configured,
* further filtering is synchronized according to the current session.
* That means that, for one user (represented through a http session) only
* one http request is processed at the same time.
*
* Only one jdbc connection can be open per user if synchronized.
*
* @param request A HttpServletRequest containing the session that is to be synchronized.
* @param response The HttpServletResponse object.
* @param chain The FilterChain object.
* @throws IOException
* @throws ServletException
*/
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException,
ServletException {
if (synchronizeUserSession) {
HttpSession session = request.getSession();
synchronized(session) {
doFilterHibernate(request, response, chain);
}
} else {
doFilterHibernate(request, response, chain);
}
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
// no synchronization needed as no http session exists
doFilterHibernate(request, response, chain);
}