KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > db > DbSession


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 import jodd.util.collection.Bag;
7 import jodd.util.collection.HashBag;
8
9 import java.sql.Connection JavaDoc;
10 import java.sql.SQLException JavaDoc;
11 import java.util.Iterator JavaDoc;
12
13 /**
14  * Encapsualtes db connection. Initially works in autocommit mode.
15  * May start and work with transactions, after commiting/rolling back
16  * DbSession goes back to autocommit mode.
17  * <p>
18  * All invoked queries are stored within one session and closed implicitly
19  * on session closing.
20  * <p>
21  * For managed transaction see {@link jodd.db.jtx.DbJtxSession}.
22  */

23 public class DbSession {
24
25     /**
26      * Default {@link DbTransactionMode} for all db sessions.
27      */

28     public static DbTransactionMode DEFAULT_TX_MODE = new DbTransactionMode();
29
30     // ---------------------------------------------------------------- init & close
31

32     protected ConnectionProvider connectionProvider;
33     protected Connection JavaDoc connection;
34
35     /**
36      * Creates new database session with default transaction mode and in autocommit mode.
37      */

38     public DbSession(ConnectionProvider connectionProvider) {
39         this.connectionProvider = connectionProvider;
40         txActive = false;
41         txMode = DEFAULT_TX_MODE;
42         queries = new HashBag();
43     }
44
45
46     /**
47      * Closes current session and all allocated resources.
48      * All attached queries are closed. If a transaction is still active, exception occurs.
49      * Database connection is returned to the {@link ConnectionProvider}.
50      * Closed session is no longer availiable for usage.
51      */

52     public void closeSession() {
53         Iterator JavaDoc it = queries.iterator();
54         while (it.hasNext()) {
55             ((DbQuery) it.next()).close();
56         }
57
58         if (connection != null) {
59             if (txActive == true) {
60                 throw new DbSqlException("Transaction was not closed before closing the session.");
61             }
62             connectionProvider.closeConnection(connection);
63             connection = null;
64         }
65
66         queries = null;
67     }
68
69     /**
70      * Indicates whether a session is open.
71      */

72     public boolean isSessionClosed() {
73         return queries == null;
74     }
75
76
77     // ---------------------------------------------------------------- query
78

79     /**
80      * Bag of all queries attached to this session. Explicitly closed queries
81      * remains in the bag. If <code>null</code> session is closed;
82      */

83     protected Bag queries;
84
85     /**
86      * Returns total number of queries assigned to this session.
87      */

88     public int getTotalQueries() {
89         return queries.size();
90     }
91
92     /**
93      * Returns total number of queries assigned to this session.
94      */

95     public int getTotalActiveQueries() {
96         int count = 0;
97         Iterator JavaDoc it = queries.iterator();
98         while (it.hasNext()) {
99             if (((DbQuery) it.next()).isActive() == true) {
100                 count++;
101             }
102         }
103         return count;
104     }
105
106
107
108     /**
109      * Returns current connection.
110      * @see #attachQuery(DbQuery)
111      */

112     public Connection JavaDoc getConnection() {
113         return connection;
114     }
115
116
117     /**
118      * Attaches a new {@link DbQuery}. Usually invoked by {@link DbQuery#DbQuery(DbSession, String, DbQueryMode)}.
119      * May be invoked both inside and outside of transaction.
120      */

121     void attachQuery(DbQuery query) {
122         checkOpenSession();
123         openConnectionForQuery();
124         queries.add(query);
125     }
126
127
128     /**
129      * Opens connection in autocommit mode, if already not opened.
130      */

131     protected void openConnectionForQuery() {
132         if (connection == null) {
133             connection = connectionProvider.getConnection();
134             txActive = false; // txAction should already be false
135
try {
136                 connection.setAutoCommit(true);
137             } catch (SQLException JavaDoc sex) {
138                 throw new DbSqlException("Unable to open non-transactional connection.", sex);
139             }
140         }
141     }
142
143     // ---------------------------------------------------------------- transaction
144

145     protected boolean txActive;
146
147     protected DbTransactionMode txMode;
148
149     /**
150      * Indicate whether a transaction is in progress.
151      */

152     public boolean isTransactionActive() {
153         return txActive;
154     }
155
156
157     /**
158      * Opens a transaction.
159      */

160     protected void openTx() {
161         if (connection == null) {
162             connection = connectionProvider.getConnection();
163         }
164         txActive = true;
165         try {
166             connection.setAutoCommit(false);
167             if (txMode.getIsolation() != DbTransactionMode.ISOLATION_DEFAULT) {
168                 connection.setTransactionIsolation(txMode.getIsolation());
169             }
170             connection.setReadOnly(txMode.isReadOnly());
171         } catch (SQLException JavaDoc sex) {
172             throw new DbSqlException("Unable to open and prepare transaction.", sex);
173         }
174     }
175
176     /**
177      * Closes current transaction.
178      */

179     protected void closeTx() {
180         txActive = false;
181         try {
182             connection.setAutoCommit(true);
183         } catch (SQLException JavaDoc sex) {
184             throw new DbSqlException("Unable to prepare connection", sex);
185         }
186     }
187
188
189     /**
190      * Starts a transaction.
191      */

192     public void beginTransaction(DbTransactionMode mode) {
193         checkClosedTx();
194         this.txMode = mode;
195         openTx();
196     }
197
198     /**
199      * Starts transaction with default transaction mode.
200      */

201     public void beginTransaction() {
202         beginTransaction(DEFAULT_TX_MODE);
203     }
204
205     /**
206      * Commit the current transaction, writing any unflushed changes to the database.
207      * Transaction mode is closed.
208      */

209     public void commitTransaction() {
210         checkActiveTx();
211         try {
212             connection.commit();
213         } catch (SQLException JavaDoc sex) {
214             throw new DbSqlException("Unable to commit transaction regulary.", sex);
215         } finally {
216             closeTx();
217         }
218     }
219
220     /**
221      * Roll back the current transaction. Transaction mode is closed.
222      */

223     public void rollbackTransaction() {
224         checkActiveTx();
225         try {
226             connection.rollback();
227         } catch (SQLException JavaDoc sex) {
228             throw new DbSqlException("Unable to rollback transaction regulary.", sex);
229         } finally {
230             closeTx();
231         }
232     }
233
234
235     // ---------------------------------------------------------------- checkings
236

237
238     protected void checkOpenSession() {
239         if (queries == null) {
240             throw new DbSqlException("Session is already closed.");
241         }
242     }
243
244     protected void checkClosedTx() {
245         checkOpenSession();
246         if (txActive == true) {
247             throw new DbSqlException("Transaction already started for this session.");
248         }
249     }
250
251     protected void checkActiveTx() {
252         checkOpenSession();
253         if (txActive == false) {
254             throw new DbSqlException("Transaction not availiable for this session.");
255         }
256     }
257 }
Popular Tags