View Javadoc

1   // $Id: SessionLocator.java,v 1.1 2004/06/24 20:54:18 powerpete Exp $
2   // [JMP, 24.06.2004] created this file.
3   package com.pnpconsult.zeiterfassung.helper;
4   
5   import net.sf.hibernate.HibernateException;
6   import net.sf.hibernate.Session;
7   import net.sf.hibernate.SessionFactory;
8   import net.sf.hibernate.cfg.Configuration;
9   
10  import org.apache.commons.logging.Log;
11  import org.apache.commons.logging.LogFactory;
12  
13  /***
14   * @author <a href="mailto:powerpete@users.sf.net">Moritz Petersen</a>
15   * @version $Id: SessionLocator.java,v 1.1 2004/06/24 20:54:18 powerpete Exp $
16   */
17  public class SessionLocator
18  {
19      private static final Log LOG = LogFactory.getLog(SessionLocator.class);
20      private static ThreadLocal store = new ThreadLocal();
21      private static SessionFactory factory;
22      
23      static
24      {
25          try
26          {
27              Configuration configuration = new Configuration().configure();
28              factory = configuration.buildSessionFactory();
29          }
30          catch (HibernateException e)
31          {
32              LOG.fatal(e.getMessage(), e);
33          }
34      }
35  
36      public static Session getSession() throws HibernateException
37      {
38          Session session = internalGetSession();
39          if (session == null || !session.isOpen())
40          {
41              session = factory.openSession();
42              store.set(session);
43          }
44          return session;
45      }
46      
47      private static Session internalGetSession()
48      {
49          return (Session) store.get();
50      }
51  
52      public static void closeSession() throws HibernateException
53      {
54          Session session = internalGetSession();
55          if (session != null)
56          {
57              session.close();
58              store.set(null);
59          }
60      }
61  }