Hi,
I use the famous pattern to use Hibernate in Struts app.
To simplify this pattern, it's like this:
HibernateUtil.java
Code:
public static final ThreadLocal sessionThread = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session session = (Session) sessionThread.get();
// Open a new Session, if this Thread has none yet
if (session == null) {
session = sessionFactory.openSession();
sessionThread.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = (Session) sessionThread.get();
sessionThread.set(null);
if (session != null){
session.close();
}
}
HibernateFilter.javaCode:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
// Call the next filter (continue request processing)
chain.doFilter(request, response);
} finally {
// No matter what happens, close the Session.
[color=red][b]HibernateUtil.closeSession();[/b][/color]
}
}
My problem, is that we close the session in the filter but what if session is using by another client that is executing a transaction?
I have done the test with two simultaneous call to the same servlet, so two transactions are opened into the same session but when the first transaction ends, it closes the sessions so that it rollbacks my second transaction that wasn't completed!
Do I say wrong?
Am I coding something wrong?
please could you help me....
(note: to be able to reproduce the problem, I have created two transactions that takes about 20sec to complete, otherwise, the first call could closes the session before the second open it!)
Thanks for your help