If you use a application server you can rewrite your class to a SessionFilter.
Just let it implement Filter and override the doFilter() method:
Code:
public class HibernateUtils implements javax.servlet.Filter {
// ... other code
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (threadLocal.get() != null) throw new IllegalStateException("A session is already associated with this thread! " + "Someone must have called getSession() outside of the context "
+ "of a servlet request.");
try {
chain.doFilter(request, response);
}
finally {
final Session sess = (Session) hibernateHolder.get();
if (sess != null) {
threadLocal.set(null);
try {
if (log.isDebugEnabled()) log.debug("Closing Hibernate Session...");
sess.close();
}
catch (HibernateException ex) {
log.error("Exception while closing Hibernate Session", ex);
throw new ServletException(ex);
}
}
}
}
// .. other code..
}