1 16 package com.ibatis.sqlmap.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.sqlmap.engine.transaction.IsolationLevel; 22 import com.ibatis.sqlmap.engine.transaction.Transaction; 23 import com.ibatis.sqlmap.engine.transaction.TransactionException; 24 25 import javax.sql.DataSource ; 26 import java.sql.Connection ; 27 import java.sql.SQLException ; 28 29 public class JdbcTransaction implements Transaction { 30 31 private static final Log connectionLog = LogFactory.getLog(Connection .class); 32 33 private DataSource dataSource; 34 private Connection connection; 35 private IsolationLevel isolationLevel = new IsolationLevel(); 36 37 public JdbcTransaction(DataSource ds, int isolationLevel) throws TransactionException { 38 dataSource = ds; 40 if (dataSource == null) { 41 throw new TransactionException("JdbcTransaction initialization failed. DataSource was null."); 42 } 43 this.isolationLevel.setIsolationLevel(isolationLevel); 44 } 45 46 private void init() throws SQLException , TransactionException { 47 connection = dataSource.getConnection(); 49 if (connection == null) { 50 throw new TransactionException("JdbcTransaction could not start transaction. Cause: The DataSource returned a null connection."); 51 } 52 isolationLevel.applyIsolationLevel(connection); 54 if (connection.getAutoCommit()) { 56 connection.setAutoCommit(false); 57 } 58 if (connectionLog.isDebugEnabled()) { 60 connection = ConnectionLogProxy.newInstance(connection); 61 } 62 } 63 64 public void commit() throws SQLException , TransactionException { 65 if (connection != null) { 66 connection.commit(); 67 } 68 } 69 70 public void rollback() throws SQLException , TransactionException { 71 if (connection != null) { 72 connection.rollback(); 73 } 74 } 75 76 public void close() throws SQLException , TransactionException { 77 if (connection != null) { 78 try { 79 isolationLevel.restoreIsolationLevel(connection); 80 } finally { 81 connection.close(); 82 connection = null; 83 } 84 } 85 } 86 87 public Connection getConnection() throws SQLException , TransactionException { 88 if (connection == null) { 89 init(); 90 } 91 return connection; 92 } 93 94 } 95 | Popular Tags |