01: package net.sourceforge.jaxor.db;
02:
03: import net.sourceforge.jaxor.api.ConnectionFactory;
04: import net.sourceforge.jaxor.api.JaxorTransaction;
05: import net.sourceforge.jaxor.util.SystemException;
06:
07: import java.sql.Connection;
08: import java.sql.SQLException;
09:
10: /**
11: * The transactions uses a single connection, sets autocommit to false.
12: * The connection is used throughout the duration of the jaxor session, then
13: * the connection is commited when commmit is called on the JaxorContext
14: * The connection is closed only when end is called on the transaction.
15: */
16: public class SingleConnectionTransaction implements JaxorTransaction {
17:
18: private transient Connection _conn;
19: private ConnectionFactory _factory;
20:
21: public SingleConnectionTransaction(Connection conn) {
22: if (conn == null)
23: throw new IllegalArgumentException(
24: "Cannot pass a null connection");
25: setupConnection(conn);
26: _conn = conn;
27: }
28:
29: public SingleConnectionTransaction(ConnectionFactory fact) {
30: _factory = fact;
31: }
32:
33: private void setupConnection(Connection conn) {
34: if (conn == null)
35: return;
36: try {
37: if (conn.getAutoCommit())
38: conn.setAutoCommit(false);
39: } catch (SQLException e) {
40: throw new SystemException(e);
41: }
42: }
43:
44: /**
45: * A connection decorator is used to prevent the connection from being closed.
46: */
47: public Connection getConnection() {
48: return net.sourceforge.jaxor.db.ConnectionDecorator
49: .createNonClosing(getConn());
50: }
51:
52: private Connection getConn() {
53: if (_conn == null) {
54: Connection conn = _factory.getConnection();
55: setupConnection(conn);
56: _conn = conn;
57: }
58: return _conn;
59: }
60:
61: public void commit() {
62: //this means a connection was never used....
63: if (notUsed())
64: return;
65: try {
66: _conn.commit();
67: } catch (SQLException e) {
68: throw new SystemException(e);
69: }
70: }
71:
72: private boolean notUsed() {
73: return _conn == null;
74: }
75:
76: public void rollback(Exception failure) {
77: if (notUsed())
78: return;
79: try {
80: _conn.rollback();
81: } catch (SQLException e) {
82: throw new SystemException(failure, e);
83: }
84: }
85:
86: public void end() {
87: if (notUsed())
88: return;
89: try {
90: _conn.close();
91: _conn = null;
92: } catch (SQLException e) {
93: throw new SystemException(e);
94: }
95: }
96:
97: }
|