1 package org.sapia.soto.hibernate; 2 3 import net.sf.hibernate.HibernateException; 4 import net.sf.hibernate.Session; 5 import net.sf.hibernate.SessionFactory; 6 7 8 16 public class SessionState { 17 static ThreadLocal _sessionRef = new ThreadLocal (); 18 19 private SessionState() { 20 super(); 21 } 22 23 29 public static void registerSession(Session sess) throws IllegalStateException { 30 if (_sessionRef.get() != null) { 31 throw new IllegalStateException ( 32 "Thread already registered with a session"); 33 } 34 35 _sessionRef.set(sess); 36 } 37 38 41 public static void unregister() { 42 _sessionRef.set(null); 43 } 44 45 51 public static Session currentSession() throws IllegalStateException { 52 Session s; 53 54 if ((s = (Session) _sessionRef.get()) == null) { 55 throw new IllegalStateException ("Thread not registered with a session"); 56 } 57 58 return s; 59 } 60 61 71 public static Session currentSession(SessionFactory fac) 72 throws HibernateException { 73 Session s; 74 75 if ((s = (Session) _sessionRef.get()) == null) { 76 s = fac.openSession(); 77 _sessionRef.set(s); 78 } 79 80 return s; 81 } 82 83 86 public static boolean isRegistered() { 87 return _sessionRef.get() != null; 88 } 89 } 90 | Popular Tags |