KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sapia > soto > hibernate > SessionState


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 /**
9  * @author Yanick Duchesne
10  * <dl>
11  * <dt><b>Copyright:</b><dd>Copyright &#169; 2002-2003 <a HREF="http://www.sapia-oss.org">Sapia Open Source Software</a>. All Rights Reserved.</dd></dt>
12  * <dt><b>License:</b><dd>Read the license.txt file of the jar or visit the
13  * <a HREF="http://www.sapia-oss.org/license.html">license page</a> at the Sapia OSS web site</dd></dt>
14  * </dl>
15  */

16 public class SessionState {
17   static ThreadLocal JavaDoc _sessionRef = new ThreadLocal JavaDoc();
18
19   private SessionState() {
20     super();
21   }
22
23   /**
24    * Registers the calling thread with the given session.
25    *
26    * @param sess a <code>Session</code>.
27    * @throws IllegalStateException if the current thread is already registered with a session.
28    */

29   public static void registerSession(Session sess) throws IllegalStateException JavaDoc {
30     if (_sessionRef.get() != null) {
31       throw new IllegalStateException JavaDoc(
32         "Thread already registered with a session");
33     }
34
35     _sessionRef.set(sess);
36   }
37
38   /**
39    * Unregisters the session that is associated to the calling thread.
40    */

41   public static void unregister() {
42     _sessionRef.set(null);
43   }
44
45   /**
46    * Returns the session that is registered with the calling thread.
47    *
48    * @return a <code>Session</code>.
49    * @throws IllegalStateException if no session is registered with the calling thread.
50    */

51   public static Session currentSession() throws IllegalStateException JavaDoc {
52     Session s;
53
54     if ((s = (Session) _sessionRef.get()) == null) {
55       throw new IllegalStateException JavaDoc("Thread not registered with a session");
56     }
57
58     return s;
59   }
60
61   /**
62    * Returns the session that is registered with the calling thread. If none
63    * is currently registered, this method uses the given session factory to
64    * create one; it registers the created session with the calling thread and returns
65    * it.
66    *
67    * @param fac a <code>SessionFactory</code>.
68    * @return a <code>Session</code>.
69    * @throws HibernateException
70    */

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   /**
84    * @return <code>true</code> if the calling thread is registered with a session.
85    */

86   public static boolean isRegistered() {
87     return _sessionRef.get() != null;
88   }
89 }
90
Popular Tags