These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 
Author Message
 Post subject: Quick Start with tomcat
PostPosted: Fri Jun 24, 2005 4:03 pm 
Beginner
Beginner

Joined: Wed May 18, 2005 9:48 am
Posts: 31
Hi,

I want to know if there is anything that could start hibernate pool with tomcat server start instead of start hibernate pool first time you create SessionFactory.

Thanks


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 24, 2005 5:57 pm 
Regular
Regular

Joined: Sun May 08, 2005 2:48 am
Posts: 118
Location: United Kingdom
Have you exhausted http://www.hibernate.org/194.html

I've looked into this idea too. Short of hacking something together for one application / development use My undertanding of it is that for it to work properly a more featureful JNDI implementation is needed inside tomcat.

This all then starts to sound like more featureful application server, like JBoss which includes a HAR Deployer mechanism which effectivly does this. It seperates the SessionFactory and its configuration from the WAR/EAR application which provides a more long running SessionFactory.

But to work effectivly it needs a more featureful JNDI implementation than what I believe tomcat provides. I think tomcat accepts static mapping of only a global JNDI tree from its configuration file but its my understanding that it does not support a dynamic JNDI tree or deal with the security requirements of having an application specific JNDI trees.

The JBoss HAR deployer auto-deploys *.har files and binds the resulting SessionFactory to JNDI dynamically this would usualy be in the scope of the web-application is was supporting.

It would seem a pitty to re-invent the wheel, it would make sense to have a simple JNDI implementation like tomcat does now but also have a pluggable more featureful JNDI implementation as a tomcat add-on that users download on top. This way the base tomcat can stay lean for applications that dont need complex JNDI support.

Then on top of this look at re-using the existing HAR deployer. This approach would seem to bring the most benifit to the most users. We get more features (if we want them) and no bloat to the base code.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Jun 24, 2005 6:06 pm 
Regular
Regular

Joined: Sun May 08, 2005 2:48 am
Posts: 118
Location: United Kingdom
After re-reading your original post maybe your only issue is in production enviroment not wanting the first hit to Hibernate to stall the users browser. My (ranting) covers the headache of Hibernate startup delays during development, the bane of my life :-).

Maybe you want to take a look at Tomcat's ServletContextListener:

In your WEB-INF/classes/com/mydomain/ApplicationLifecycleListener.class file compile something like:

Code:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ApplicationLifecycleListener implements ServletContextListener {
   private static org.apache.commons.logging.Log log =
      org.apache.commons.logging.LogFactory.getLog(ApplicationLifecycleListener.class);

   public void contextInitialized(ServletContextEvent sce) {
      log.debug("contextInitialized on " + sce.getServletContext());
                // Create your SessionFacory here, from me I suppose I can just invoke the Singleton
                HibernateSession.currentSession();
                HibernateSession.closeSession();
      log.debug("contextInitialized on " + sce.getServletContext() + " done!");
   }

   public void contextDestroyed(ServletContextEvent sce) {
      log.debug("contextDestroyed on " + sce.getServletContext());
                // NOP
      log.debug("contextDestroyed on " + sce.getServletContext() + " done!");
   }
}


In WEB-INF/web.xml (in the correct place):

Code:
<listener>
<listener-class>com.mydomain.ApplicationLifecycleListener</listener-class>
</listener>


Top
 Profile  
 
 Post subject:
PostPosted: Sun Jun 26, 2005 5:46 am 
Beginner
Beginner

Joined: Wed May 18, 2005 9:48 am
Posts: 31
Ok,
I'll see, but if i used for example de eventlistener from website at http://hibernate.bluemars.net/133.html i have to remake my hibernate conection pool?.

The oConexion.java is like that:

Code:
/*
* oConexion.java
*
* Created on 21 de marzo de 2005, 14:30
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/

package bbdd;

/**
*
* @author Administrador
*/
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.*;
import exceptions.bbddExceptions;
import bbdd.dao.UsuariosDAO;

import javax.naming.*;


public class oConexion {

   private static Log log = LogFactory.getLog(oConexion.class);

   private static Configuration configuration;
   private static SessionFactory sessionFactory;
   private static final ThreadLocal threadSession = new ThreadLocal();
   private static final ThreadLocal threadTransaction = new ThreadLocal();
   private static final ThreadLocal threadInterceptor = new ThreadLocal();

   // Crea una sesion desde el archivo por defecto
   static {
      try {
         sessionFactory = new Configuration().configure().buildSessionFactory();
         // We could also let Hibernate bind it to JNDI:
         // configuration.configure().buildSessionFactory()
      } catch (Throwable ex) {
         // We have to catch Throwable, otherwise we will miss
         // NoClassDefFoundError and other subclasses of Error
         log.error("Building SessionFactory failed.", ex);
         throw new ExceptionInInitializerError(ex);
      }
   }

   /**
    * Devuelve la sesion creada por la clase.
    *
    * @return SessionFactory
    */
   public static SessionFactory getSessionFactory() {
      /* Instead of a static variable, use JNDI:
      SessionFactory sessions = null;
      try {
         Context ctx = new InitialContext();
         String jndiName = "java:hibernate/HibernateFactory";
         sessions = (SessionFactory)ctx.lookup(jndiName);
      } catch (NamingException ex) {
         throw new bbddExceptions(ex);
      }
      return sessions;
      */
      return sessionFactory;
   }

   /**
    * Devuelve la configuracion por defecto de hibernate.
    *
    * @return Configuration
    */
   public static Configuration getConfiguration() {
      return configuration;
   }

   /**
    * Reconstruye la conexion con los parametros por defecto.
    *
    */
    public static void rebuildSessionFactory()
      throws bbddExceptions {
      synchronized(sessionFactory) {
         try {
            sessionFactory = getConfiguration().buildSessionFactory();
         } catch (Exception ex) {
            throw new bbddExceptions(ex);
         }
      }
    }

   /**
    * Reconstruye la conexion con los parametros dados.
    *
    * @param cfg
    */
    public static void rebuildSessionFactory(Configuration cfg)
      throws bbddExceptions {
      synchronized(sessionFactory) {
         try {
            sessionFactory = cfg.buildSessionFactory();
            configuration = cfg;
         } catch (Exception ex) {
            throw new bbddExceptions(ex);
         }
      }
    }

   /**
    * Retrieves the current Session local to the thread.
    * <p/>
    * If no Session is open, opens a new Session for the running thread.
    *
    * @return Session
    */
   public static Session getSession()
      throws bbddExceptions {
      Session s = (Session) threadSession.get();
      try {
         if (s == null) {
            log.debug("Abriendo nueva sesion para este proceso.");
            if (getInterceptor() != null) {
               log.debug("Usando el interceptor: " + getInterceptor().getClass());
               s = getSessionFactory().openSession(getInterceptor());
            } else {
               s = getSessionFactory().openSession();
            }
            threadSession.set(s);
         }
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      }
      return s;
   }

   /**
    * Closes the Session local to the thread.
    */
   public static void closeSession()
      throws bbddExceptions {
      try {
         Session s = (Session) threadSession.get();
         threadSession.set(null);
         if (s != null && s.isOpen()) {
            log.debug("Cerrando sesion para el proceso.");
            s.close();
         }
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      }
   }

   /**
    * Comienzo de una transaccion en la BBDD.
    */
   public static void beginTransaction()
      throws bbddExceptions {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         if (tx == null) {
            log.debug("Comenzando nueva transaccion en la bbdd para el proceso.");
            tx = getSession().beginTransaction();
            threadTransaction.set(tx);
         }
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      }
   }

   /**
    * Guarda cambios en la bbdd.
    */
   public static void commitTransaction()
      throws bbddExceptions {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         if ( tx != null && !tx.wasCommitted()
                     && !tx.wasRolledBack() ) {
            log.debug("Guardando cambios en la bbdd para este proceso.");
            tx.commit();
         }
         threadTransaction.set(null);
      } catch (HibernateException ex) {
         rollbackTransaction();
         throw new bbddExceptions(ex);
      }
   }

   /**
    * Rollback de los cambios en la bbdd.
    */
   public static void rollbackTransaction()
      throws bbddExceptions {
      Transaction tx = (Transaction) threadTransaction.get();
      try {
         threadTransaction.set(null);
         if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
            log.debug("Intentando realizar rollback de la bbdd para este proceso.");
            tx.rollback();
         }
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      } finally {
         closeSession();
      }
   }

   /**
    * Reconecta la sesion del hibernate al proceso.
    *
    * @param session The Hibernate Session to be reconnected.
    */
   public static void reconnect(Session session)
      throws bbddExceptions {
      try {
         session.reconnect();
         threadSession.set(session);
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      }
   }

   /**
    * Disconnect and return Session from current Thread.
    *
    * @return Session the disconnected Session
    */
   public static Session disconnectSession()
      throws bbddExceptions {

      Session session = getSession();
      try {
         threadSession.set(null);
         if (session.isConnected() && session.isOpen())
            session.disconnect();
      } catch (HibernateException ex) {
         throw new bbddExceptions(ex);
      }
      return session;
   }

   /**
    * Register a Hibernate interceptor with the current thread.
    * <p>
    * Every Session opened is opened with this interceptor after
    * registration. Has no effect if the current Session of the
    * thread is already open, effective on next close()/getSession().
    */
   public static void registerInterceptor(Interceptor interceptor) {
      threadInterceptor.set(interceptor);
   }

   private static Interceptor getInterceptor() {
      Interceptor interceptor = (Interceptor) threadInterceptor.get();
      return interceptor;
   }
}


Thanks a lot.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.