0
votes

I am handling some old application code, and there seems to be several concepts involved, so I am looking to make sure I can improve them into one solid and strict practice.

Basically, the whole code is wrapped with a HibernateSessionRequestFilter like this

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        sf.getCurrentSession().beginTransaction();            

        chain.doFilter(request, response);

        sf.getCurrentSession().clear();

    } catch (...) {        
        //...
    } finally {
        sf.getCurrentSession().close();
    }

}

Then, there is an interceptor, doing something like this

private String loadStaff(...) {
    //...

    try {
        dbSession = //...;
        dbSession.beginTransaction();

        // some logic

        dbSession.getTransaction().rollback();

    } catch (RuntimeException e) {
        //..
    }
    finally {
        if (dbSession != null && dbSession.isOpen()) {
            dbSession.clear();
        }
    }
    }

And then there is even more business logic code with some more begintransactions and session clear etc.

So, questions:

  1. What happens when beginTransaction called more than once on same session?
  2. Sometimes, calling "clear()" throws exception, I think it happens after a "rollback()" was called. How to fix that?
  3. In general, what is the best proposed practice to combine session.clear() with transaction begin/rollback/commit ?

Thank you

1
Why do you clear the session in the first place? What do you think it does? Why do you rollback the transaction, and not commit it? What do you think it does? Have your read the javadoc of those methods, and the javadoc of beginTransaction, which does say what happens when it's called multiple times on the same session. Have you read docs.jboss.org/hibernate/orm/5.1/userguide/html_single/…, which explains how to use transactions? - JB Nizet

1 Answers

1
votes

Your code should look like this and this is way to handle the transaction for the single http request,

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        // Open the transaction.
        sf.getCurrentSession().beginTransaction();            

        // Handle the request
        chain.doFilter(request, response);

        // Persist the db changes into database.
        sf.getCurrentSession().commit();

    } catch (...) {        
        // Somthing gone wrong while handling the http request so we should remove all the changes and rollback the changes that are done in the current request.
        sf.getCurrentSession().rollback()
    } finally {
        sf.getCurrentSession().close();
    }

}

In other parts of your code should not handle the begintransaction/close/commit the transaction. It should be handled by in one place only.