-->
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.  [ 2 posts ] 
Author Message
 Post subject: Snippet: Hibernate container listener
PostPosted: Tue Sep 02, 2003 5:18 pm 
Beginner
Beginner

Joined: Tue Aug 26, 2003 4:19 pm
Posts: 42
Perhaps someone will find this handy. I tweaked the Struts plugin example code to work as a listener, not dependent on Struts, though it requires Servlet 2.3. It listens for a contextInitialized event and sticks a SessionFactory in the application scope.

Code:
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Session;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Databinder;
import net.sf.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class HibernateListener
   implements HttpSessionListener, ServletContextListener {


    /**
     * the key under which the <code>SessionFactory</code> instance is stored
     * in the <code>ServletContext</code>.
     */
    public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();

    private static Log _log = LogFactory.getLog(HibernateListener.class);

    private static ServletContext context = null;

    /**
     * the path to the xml configuration file.  the path should start with a
     * '/' character and be relative to the root of the class path.
     * (DEFAULT:  "/hibernate.cfg.xml")
     */
    private String _configFilePath = "/hibernate.cfg.xml";
    private SessionFactory _factory = null;

   public HibernateListener() {
   }

   public void contextInitialized(ServletContextEvent sce) {
        Configuration configuration = null;
        URL configFileURL = null;
        context = null;

        try {
            configFileURL = HibernateListener.class.getResource(_configFilePath);

            context = sce.getServletContext();

            if (_log.isWarnEnabled()) {
                _log.debug("Initializing Hibernate from "
                        + _configFilePath + "...");
            }

            configuration = (new Configuration()).configure(configFileURL);
            _factory = configuration.buildSessionFactory();
            _log.debug("Storing SessionFactory in ServletContext...");
            context.setAttribute(SESSION_FACTORY_KEY, _factory);


        } catch (Throwable t) {
            _log.error("Exception while initializing Hibernate.");
            System.out.println("Exception while initializing Hibernate.");
            t.printStackTrace();
        }
   }


   public void contextDestroyed(ServletContextEvent sce) {

        try {
            _log.debug("Destroying SessionFactory...");
            _factory.close();
            _log.debug("SessionFactory destroyed...");
        } catch (Exception e) {
            _log.error("Unable to destroy SessionFactory...(exception ignored)",
                    e);
        }
   }

   public void sessionCreated(HttpSessionEvent se) {
        //required by Listener contract.  We're creating Hibernate sessions per-request so we don't care about this.
   }

   public void sessionDestroyed(HttpSessionEvent se) {
        //required by Listener contract.
   }

    public static SessionFactory sessionFactory(HttpServletRequest request)
            throws HibernateException {
        Object sf = context.getAttribute(SESSION_FACTORY_KEY);
        if (null == sf) {
            throw new HibernateException(SESSION_FACTORY_KEY);
        }
        return (SessionFactory) sf;
    }
    public static Session open(HttpServletRequest request) throws HibernateException {

        Session sess = null;
        try {
            sess = sessionFactory(request).openSession();
        } catch (HibernateException e) {
            e.printStackTrace();
        }

        return sess;

    }

    public static Databinder openDB(HttpServletRequest request) throws HibernateException {

        Databinder db = null;
        try {
            db = sessionFactory(request).openDatabinder();
        } catch (HibernateException e) {
            e.printStackTrace();
        }

        return db;

    }

}
[/quote]


Top
 Profile  
 
 Post subject:
PostPosted: Tue Sep 02, 2003 7:26 pm 
Hibernate Team
Hibernate Team

Joined: Tue Aug 26, 2003 12:50 pm
Posts: 5130
Location: Melbourne, Australia
Its better to put this kind of thing on the wiki :)


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 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.