Version 2

    In a simple web application, where the web tier has direct access to the database, it makes sense to define a persistence-aware superclass for actions that use Hibernate. The superclass should implement logging, exception handling and Session instantiation. The following example uses WebWork, but the ideas are applicable to other frameworks.

    public class HibernateAction extends ActionSupport {
    
       private static final Log LOG = LogFactory.getLog(HibernateAction.class);
       private Session session;
    
       protected String invokeCommand() throws Exception {
    
          LOG.trace("Opening Hibernate session");
          SessionFactory sf = (SessionFactory) ActionContext.getContext()
              .getApplication()
              .get("SessionFactory");
          if (sf==null) sf = buildSessionFactory();
          session = sf.openSession();
          session.setFlushMode( getFlushMode() );
    
          Transaction tx = null;
          try {
             tx = session.beginTransaction();
             LOG.trace("Invoking Action command");
             super.invokeCommand();
             LOG.trace("Committing Hibernate Transaction");
             tx.commit();
          }
          catch (Exception e) {
             LOG.error("Exception invoking Action command or committing Hibernate Transaction", e);
             if (tx!=null) tx.rollback();
             throw e;
          }
          finally {
             session.close();
          }
    
       }
       
       protected final Session getSession() {
          return session;
       }
    
       protected FlushMode getFlushMode() {
          return FlushMode.AUTO;
       }
    
       private SessionFactory buildSessionFactory() {
          // Create a SessionFactory and store it in Application context
       }
    
    }