KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > db > DbThreadSession


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.db;
4
5 import jodd.db.connection.ConnectionProvider;
6
7 /**
8  * Thread assigned {@link jodd.db.DbSession}. Upon creation, it assigns
9  * the session to current thread. Useful when only one session (i.e. connection)
10  * is used per thread, through service layers.
11  */

12 public class DbThreadSession extends DbSession {
13
14     /**
15      * Creates a new db session and assign it to current thread.
16      * Closes already assigned session, if any exist.
17      * @param connectionProvider
18      */

19     public DbThreadSession(ConnectionProvider connectionProvider) {
20         super(connectionProvider);
21         DbThreadSession session = (DbThreadSession) SESSION.get();
22         if (session != null) {
23             session.closeSession();
24         }
25         SESSION.set(this);
26     }
27     
28     private static final ThreadLocal JavaDoc SESSION = new ThreadLocal JavaDoc() {
29         protected synchronized Object JavaDoc initialValue() {
30             return null;
31         }
32      };
33
34     /**
35      * Returns current thread session od <code>null</code> if no session assigned
36      * to a thread.
37      */

38     public static DbSession getCurrentSession() {
39         return (DbSession) SESSION.get();
40     }
41
42
43     /**
44      * Closes current session and remove the assotiation from current thread.
45      * @see jodd.db.DbSession#closeSession()
46      */

47     public void closeSession() {
48         super.closeSession();
49         SESSION.set(null);
50     }
51 }
52
Popular Tags