1 4 5 package org.enhydra.shark.transaction; 6 7 import net.sf.hibernate.HibernateException; 8 import net.sf.hibernate.Session; 9 import net.sf.hibernate.SessionFactory; 10 import net.sf.hibernate.cfg.Configuration; 11 import org.enhydra.shark.api.RootError; 12 13 17 public class ThreadLocalSession { 18 19 private static final SessionFactory sessionFactory; 20 public static final ThreadLocal threadLocal = new ThreadLocal (); 21 22 static { 23 try { 24 sessionFactory = new Configuration().configure( 25 "/hibernate.instance.cfg.xml").buildSessionFactory(); 26 } catch (HibernateException ex) { 27 throw new RootError("Exception building SessionFactory: " 28 + ex.getMessage(), ex); 29 } 30 } 31 32 public static Session currentSession() throws HibernateException { 33 Session session = (Session) threadLocal.get(); 34 if (session == null) { 36 session = sessionFactory.openSession(); 37 threadLocal.set(session); 38 } 39 if (!session.isConnected()){ 40 session.reconnect(); 41 } 42 return session; 43 44 } 45 46 public static void closeSession() throws HibernateException { 47 Session session = (Session) threadLocal.get(); 48 threadLocal.set(null); 49 if (session != null) 50 session.close(); 51 } 52 53 } 54 | Popular Tags |