1 package cash.util; 2 3 4 5 import net.sf.hibernate.HibernateException; 6 7 import net.sf.hibernate.SessionFactory; 8 9 import net.sf.hibernate.Session; 10 11 import net.sf.hibernate.cfg.Configuration; 12 13 14 15 import org.apache.log4j.Logger; 16 17 18 19 30 31 public class HibernateUtil { 32 33 34 35 36 37 public static final ThreadLocal MAP = new ThreadLocal (); 38 39 40 41 private static final Logger LOG = Logger.getLogger(HibernateUtil.class); 42 43 44 45 private static final SessionFactory SESSION_FACTORY; 46 47 48 49 50 51 private HibernateUtil() { } 52 53 54 55 56 57 static { 58 59 try { 60 61 LOG.debug("HibernateUtil.static - loading config"); 62 63 SESSION_FACTORY = new Configuration().configure().buildSessionFactory(); 64 65 LOG.debug("HibernateUtil.static - end"); 66 67 } catch (HibernateException ex) { 68 69 throw new RuntimeException ("Exception building SessionFactory: " + ex.getMessage(), ex); 70 71 } 72 73 } 74 75 76 77 88 89 public static Session currentSession() throws HibernateException { 90 91 Session s = (Session)MAP.get(); 92 93 95 if (s == null) { 96 97 s = SESSION_FACTORY.openSession(); 98 99 MAP.set(s); 100 101 } 102 103 return s; 104 105 } 106 107 108 109 118 119 public static void closeSession() throws HibernateException { 120 121 Session s = (Session)MAP.get(); 122 123 MAP.set(null); 124 125 if (s != null) { 126 127 s.close(); 128 129 } 130 131 } 132 133 } | Popular Tags |