1 4 5 package org.enhydra.shark.processlocking; 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.processlocking.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 public static void closeSession() throws HibernateException { 41 Session session = (Session) threadLocal.get(); 42 threadLocal.set(null); 43 if (session != null) 44 session.close(); 45 } 46 } 47 | Popular Tags |