1 package org.sapia.regis.hibernate; 2 3 import org.hibernate.Session; 4 5 public class Sessions { 6 7 private static ThreadLocal sessions = new ThreadLocal (); 8 9 public static Session get(){ 10 if(sessions.get() == null){ 11 throw new IllegalStateException ("Calling thread not registered with session"); 12 } 13 Session s = (Session)sessions.get(); 14 if(!s.isOpen()){ 15 s = s.getSessionFactory().openSession(); 16 sessions.set(s); 17 } 18 return s; 19 } 20 21 public static void join(Session session){ 22 sessions.set(session); 23 } 24 25 public static void close(){ 26 if(sessions.get() != null){ 27 Session s = (Session)sessions.get(); 28 try{ 29 s.flush(); 30 }catch(RuntimeException e){ 31 s.close(); 32 sessions.set(null); 33 throw e; 34 } 35 s.close(); 36 sessions.set(null); 37 } 38 } 39 40 41 public static boolean isRegistered(){ 42 return sessions.get() != null; 43 } 44 } 45 | Popular Tags |