|
From: Artem P. <bla...@ca...> - 2005-11-21 01:29:28
|
Some Web application frameworks like JSF might require you to extend the
lifetime of a persistent entity beyond a single HTTP request. What I am
proposing is an alternative implementation of OpenSessionInViewFilter that
opens one Hibernate session per HTTP session instead of one session per
request. JDBC connection management should not be a problem because it is
possible to disconnect and reconnect Hibernate sessions without closing
them.
Here is the filter that I'm using in my application... I think it would be a
good idea to include something similar in a future release of Spring. Please
note that it hasn't been well tested, and it requires a session filter that
closes orphaned sessions.
public class HibernateSessionFilter extends OncePerRequestFilter {
public static final String DEFAULT_SESSION_FACTORY_BEAN_NAME =
"sessionFactory";
public static final String SESSION_KEY = "org.foo.web.hibernateSession";
private String sessionFactoryBeanName = DEFAULT_SESSION_FACTORY_BEAN_NAME;
/**
* @return Returns the sessionFactoryBeanName.
*/
protected String getSessionFactoryBeanName() {
return sessionFactoryBeanName;
}
/**
* @param sessionFactoryBeanName The sessionFactoryBeanName to set.
*/
public void setSessionFactoryBeanName(String sessionFactoryBeanName) {
this.sessionFactoryBeanName = sessionFactoryBeanName;
}
protected SessionFactory lookupSessionFactory() {
if (logger.isDebugEnabled()) {
logger.debug("Using SessionFactory '" + getSessionFactoryBeanName() + "'
for OpenSessionInViewFilter");
}
WebApplicationContext wac =
WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
return (SessionFactory) wac.getBean(getSessionFactoryBeanName(),
SessionFactory.class);
}
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain
filterChain)
throws ServletException, IOException {
SessionFactory sessionFactory = lookupSessionFactory();
HttpSession httpSession = request.getSession();
Session session =
(Session) httpSession.getAttribute(SESSION_KEY);
if (session == null) {
session = sessionFactory.openSession();
httpSession.setAttribute(SESSION_KEY, session);
}
if (!session.isConnected()) {
session.reconnect();
}
TransactionSynchronizationManager.bindResource(sessionFactory, new
SessionHolder(session));
try {
filterChain.doFilter(request, response);
} finally {
TransactionSynchronizationManager.unbindResource(sessionFactory);
session.disconnect();
}
}
}
|