1 4 5 package org.enhydra.shark.appmappersistence; 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 public static final ThreadLocal threadLocal = new ThreadLocal (); 17 18 static { 19 try { 20 sessionFactory = new Configuration().configure( 21 "/hibernate.applicationmapping.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 30 Session session = (Session) threadLocal.get(); 31 if (session == null) { 33 session = sessionFactory.openSession(new AppMappingsInterceptor()); 34 threadLocal.set(session); 35 } 36 if (!session.isConnected()){ 37 session.reconnect(); 38 } 39 return session; 40 } 41 42 public static void closeSession() throws HibernateException { 43 Session session = (Session) threadLocal.get(); 44 threadLocal.set(null); 45 if (session != null) 46 session.close(); 47 } 48 } 49 | Popular Tags |