Hi,
I see two options:
1. Long running Hibernate sessions: implemet a filter that takes care of session lookup + flush + other details:
Code:
public class LongRunningHibernateSessionFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
//looks up the session from the HTTP session
Session session = lookupSession(request);
if(session == null){
//create a new Hibernate session and stopre it in the HTTP session
session = createSession();
}
session.connect();
if (!TransactionSynchronizationManager.hasResource(sessionFactory)) {
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
}
filterChain.doFilter(request, response);
//flush the changes to the database
session.flush();
session.disconnect();
}
Maybe you might want to change/adjust when the Hibernate session is flushed according to your use cases. Also, it would make sense to have a HttpSessionListener that creates and destroys the Hibernate session.
2. Hibernate session per request + OpenSessionInViewFilter + reatach objects filter:
Code:
public class ReatachFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
Session session = lookupSession();
Enumeration en = request.getSession().getAttributeNames();
while (en.hasMoreElements()){
String attrName = (String) en.nextElement();
Object o = request.getSession().getAttribute(attrName);
try {
session.lock(o, LockMode.NONE);
} catch (HibernateException e) {
//just ignore this error, maybe this object
//does not have a hibernate mapping
}
}
filterChain.doFilter(request, response);
}
}
In this case maybe you would like to refine what objects get re-attached to the Hibernate session.
Cheers, Mircea