KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibatis > dao > engine > transaction > jdbc > JdbcDaoTransaction


1 /*
2  * Copyright 2004 Clinton Begin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package com.ibatis.dao.engine.transaction.jdbc;
17
18 import com.ibatis.common.jdbc.logging.ConnectionLogProxy;
19 import com.ibatis.common.logging.Log;
20 import com.ibatis.common.logging.LogFactory;
21 import com.ibatis.dao.client.DaoException;
22 import com.ibatis.dao.engine.transaction.ConnectionDaoTransaction;
23
24 import javax.sql.DataSource JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.SQLException JavaDoc;
27
28 public class JdbcDaoTransaction implements ConnectionDaoTransaction {
29
30   private static final Log connectionLog = LogFactory.getLog(Connection JavaDoc.class);
31
32   private Connection JavaDoc connection;
33
34   public JdbcDaoTransaction(DataSource JavaDoc dataSource) {
35     try {
36       connection = dataSource.getConnection();
37       if (connection == null) {
38         throw new DaoException("Could not start transaction. Cause: The DataSource returned a null connection.");
39       }
40       if (connection.getAutoCommit()) {
41         connection.setAutoCommit(false);
42       }
43       if (connectionLog.isDebugEnabled()) {
44         connection = ConnectionLogProxy.newInstance(connection);
45       }
46     } catch (SQLException JavaDoc e) {
47       throw new DaoException("Error starting JDBC transaction. Cause: " + e);
48     }
49   }
50
51
52   public void commit() {
53     try {
54       try {
55         connection.commit();
56       } finally {
57         connection.close();
58       }
59     } catch (SQLException JavaDoc e) {
60       throw new DaoException("Error committing JDBC transaction. Cause: " + e);
61     }
62   }
63
64   public void rollback() {
65     try {
66       try {
67         connection.rollback();
68       } finally {
69         connection.close();
70       }
71     } catch (SQLException JavaDoc e) {
72       throw new DaoException("Error ending JDBC transaction. Cause: " + e);
73     }
74   }
75
76   public Connection JavaDoc getConnection() {
77     return connection;
78   }
79
80 }
81
Popular Tags