1 package org.apache.torque.util; 2 3 21 22 import java.sql.Connection ; 23 import java.sql.SQLException ; 24 25 import org.apache.commons.logging.Log; 26 import org.apache.commons.logging.LogFactory; 27 28 import org.apache.torque.Torque; 29 import org.apache.torque.TorqueException; 30 31 47 public final class Transaction 48 { 49 50 51 private static Log log = LogFactory.getLog(Transaction.class); 52 53 59 private Transaction() 60 { 61 } 62 63 73 public static Connection begin() throws TorqueException 74 { 75 return Transaction.begin(Torque.getDefaultDB()); 76 } 77 78 88 public static Connection begin(String dbName) throws TorqueException 89 { 90 return Transaction.beginOptional(dbName, true); 91 } 92 93 104 public static Connection beginOptional(String dbName, 105 boolean useTransaction) 106 throws TorqueException 107 { 108 Connection con = Torque.getConnection(dbName); 109 try 110 { 111 if (con.getMetaData().supportsTransactions() && useTransaction) 112 { 113 con.setAutoCommit(false); 114 } 115 } 116 catch (SQLException e) 117 { 118 throw new TorqueException(e); 119 } 120 return con; 121 } 122 123 132 public static void commit(Connection con) throws TorqueException 133 { 134 if (con == null) 135 { 136 throw new NullPointerException ("Connection object was null. " 137 + "This could be due to a misconfiguration of the " 138 + "DataSourceFactory. Check the logs and Torque.properties " 139 + "to better determine the cause."); 140 } 141 142 try 143 { 144 if (con.getMetaData().supportsTransactions() 145 && con.getAutoCommit() == false) 146 { 147 con.commit(); 148 con.setAutoCommit(true); 149 } 150 } 151 catch (SQLException e) 152 { 153 throw new TorqueException(e); 154 } 155 finally 156 { 157 Torque.closeConnection(con); 158 } 159 } 160 161 171 public static void rollback(Connection con) throws TorqueException 172 { 173 if (con == null) 174 { 175 throw new TorqueException("Connection object was null. " 176 + "This could be due to a misconfiguration of the " 177 + "DataSourceFactory. Check the logs and Torque.properties " 178 + "to better determine the cause."); 179 } 180 else 181 { 182 try 183 { 184 if (con.getMetaData().supportsTransactions() 185 && con.getAutoCommit() == false) 186 { 187 con.rollback(); 188 con.setAutoCommit(true); 189 } 190 } 191 catch (SQLException e) 192 { 193 log.error("An attempt was made to rollback a transaction " 194 + "but the database did not allow the operation to be " 195 + "rolled back.", e); 196 throw new TorqueException(e); 197 } 198 finally 199 { 200 Torque.closeConnection(con); 201 } 202 } 203 } 204 205 213 public static void safeRollback(Connection con) 214 { 215 if (con == null) 216 { 217 log.debug("called safeRollback with null argument"); 218 } 219 else 220 { 221 try 222 { 223 Transaction.rollback(con); 224 } 225 catch (TorqueException e) 226 { 227 log.warn("An error occured during rollback.", e); 228 } 229 } 230 } 231 } 232 | Popular Tags |