Hibernate version: 2
As per the new Hibernate In Action I implemented a HibernateFilter to utilize a request scoped transaction.
Weird issue is that it appears the filter only commits after a second request. i.e. click link 'saveStuff'
check database (nada)
click any other link
save from step 1 is commited from filter
Did I do something obvious? I did some searching and it appears the new SpringFramework version has a built in 'org.springframework.orm.hibernate.support.OpenSessionInViewFilter' which appears to be the same thing. Must I use this? OR should this be correct:
public class HibernateFilter
implements Filter {
private static final String HTTPSESSIONKEY = "HibernateSession";
private static Log log = LogFactory.getLog(HibernateFilter.class);
public void init(FilterConfig filterConfig) throws ServletException {
log.info("Servlet filter init, now disconnecting/reconnecting a Session for each request.");
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
log.debug("HibernateFilter.doFilter()");
// Try to get a Hibernate Session from the HttpSession
HttpSession userSession =
((HttpServletRequest) request).getSession();
Session hibernateSession =
(Session) userSession.getAttribute(HTTPSESSIONKEY);
if (hibernateSession != null)
HibernateSession.reconnect(hibernateSession);
// If there is no Session, the first call to
// HibernateSession.beginTransaction in application code will open
// a new Session for this thread.
try {
chain.doFilter(request, response);
// Commit any pending database transaction.
HibernateSession.commitTransaction();
log.debug("Committed Transaction!");
}catch(Throwable t){
t.printStackTrace();
log.fatal("Fatal error closing transaction in filter", t);
}
finally {
// TODO: The Session should be closed if a fatal exceptions occurs
// No matter what happens, disconnect the Session.
hibernateSession = HibernateSession.disconnectSession();
log.debug("Disconnected Session!");
// and store it in the users HttpSession
userSession.setAttribute(HTTPSESSIONKEY, hibernateSession);
}
}
public void destroy() {
}
}
Along with:
<filter>
<filter-name>HibernateFilter</filter-name>
<filter-class>com.shopbotz.servlet.HibernateFilter2</filter-class>
</filter>
<filter-mapping>
<filter-name>HibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Note: the Transaction is started in the Dao constructor as such:
public HibernateDao() {
HibernateSession.beginTransaction();
}
|