Member Menu
 
 Monthly JBoss newsletter:
 
Hibernate Books
CaveatEmptor

Hibernate Aware Action

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
   }

}

  NEW COMMENT

how to handle objects that are loaded lazily? 15 Sep 2004, 23:20 yueyuezhou
I guess you have turn off the feature if the object is going to be 
rendered in the jsp? Is there a better way?
 
Re: how to handle objects that are loaded lazily? 28 Dec 2004, 04:15 silentcat
On 15 Sep 2004 23:20, yueyuezhou wrote:

>I guess you have turn off the feature if the object is going to be
>rendered in the jsp? Is there a better way?

Hi there,
    I face the same problem with lazy=true collections. Now I have to 
turn off the lazy flag when I want to render it in jsp. Any good idea?
 
© Copyright 2006, Red Hat Middleware, LLC. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc. [Privacy Policy]