1 4 5 package org.enhydra.shark.usertransaction; 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 public class ThreadLocalSession { 14 15 private static final SessionFactory sessionFactory; 16 private static final ThreadLocal threadLocal = new ThreadLocal (); 17 18 static { 19 try { 20 sessionFactory = new Configuration().configure( 21 "/hibernate.user.cfg.xml").buildSessionFactory(); 22 } catch (HibernateException ex) { 23 throw new RootError("Exception building SessionFactory: " 24 + ex.getMessage(), ex); 25 } 26 } 27 28 public static Session currentSession() throws HibernateException { 29 Session session = (Session) threadLocal.get(); 30 if (session == null) { 32 session = sessionFactory.openSession(); 33 threadLocal.set(session); 34 } 35 if (!session.isConnected()){ 36 session.reconnect(); 37 } 38 return session; 39 } 40 41 public static void closeSession() throws HibernateException { 42 Session session = (Session) threadLocal.get(); 43 threadLocal.set(null); 44 if (session != null) 45 session.close(); 46 } 47 } 48 | Popular Tags |