1 package org.apache.turbine.util.hibernate; 2 3 18 19 import net.sf.hibernate.HibernateException; 20 import net.sf.hibernate.JDBCException; 21 import net.sf.hibernate.Session; 22 import net.sf.hibernate.SessionFactory; 23 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 27 34 public class HibernateUtils 35 { 36 public final static String SESSION_FACTORY = "hibernate/sessionFactory"; 38 public static final ThreadLocal session = new ThreadLocal (); 39 private static SessionFactory sf = null; 40 private static HibernateUtils me; 41 private static Log log = LogFactory.getLog(HibernateUtils.class); 42 43 static { 44 try 45 { 46 me = new HibernateUtils(); 47 } 48 catch (Exception e) 49 { 50 log.fatal("Error occurred initializing HibernateUtils"); 51 e.printStackTrace(); 52 } 53 } 54 55 57 private HibernateUtils() throws HibernateException, JDBCException 58 {} 59 60 62 public static Session currentSession() throws PersistenceException 63 { 64 Session s = (Session) session.get(); 65 66 if (s == null) 67 { 68 s = PersistenceManager.openSession(); 69 if (log.isDebugEnabled()) 70 { 71 log.debug("Opened hibernate session."); 72 } 73 74 session.set(s); 75 } 76 77 return s; 78 } 79 80 public static void closeSession() throws HibernateException, JDBCException 81 { 82 Session s = (Session) session.get(); 83 session.set(null); 84 85 if (s != null) 86 { 87 if (s.isOpen()) 88 { 89 s.flush(); 90 s.close(); 91 92 if (log.isDebugEnabled()) 93 { 94 log.debug("Closed hibernate session."); 95 } 96 } 97 } 98 else 99 { 100 log.warn("Hibernate session was inadvertently already closed."); 101 102 } 103 } 104 } 105 | Popular Tags |