01: // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
02:
03: package jodd.db;
04:
05: import jodd.db.connection.ConnectionProvider;
06:
07: /**
08: * Thread assigned {@link jodd.db.DbSession}. Upon creation, it assigns
09: * 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<DbSession> SESSION = new ThreadLocal<DbSession>() {
29: @Override
30: protected synchronized DbSession initialValue() {
31: return null;
32: }
33: };
34:
35: /**
36: * Returns current thread session od <code>null</code> if no session assigned
37: * to a thread.
38: */
39: public static DbSession getCurrentSession() {
40: return SESSION.get();
41: }
42:
43: /**
44: * Closes current session and remove the assotiation from current thread.
45: * @see jodd.db.DbSession#closeSession()
46: */
47: @Override
48: public void closeSession() {
49: super.closeSession();
50: SESSION.set(null);
51: }
52: }
|