1 package com.imcode.db.commands;
2
3 import com.imcode.db.DatabaseCommand;
4 import com.imcode.db.DatabaseConnection;
5 import com.imcode.db.DatabaseException;
6 import org.apache.commons.lang.UnhandledException;
7
8 import java.sql.Connection;
9 import java.sql.SQLException;
10
11 /***
12 An abstract DatabaseCommand that can be overridden to run something in an transaction.
13 **/
14 public abstract class TransactionDatabaseCommand implements DatabaseCommand {
15
16 public Object executeOn( DatabaseConnection dc ) throws DatabaseException {
17 try {
18 Connection connection = dc.getConnection() ;
19 try {
20 connection.setAutoCommit( false );
21 Object result = executeInTransaction( dc );
22 connection.commit();
23 return result;
24 } catch ( Throwable t ) {
25 connection.rollback();
26 if (t instanceof RuntimeException) {
27 throw (RuntimeException)t ;
28 } else {
29 throw new UnhandledException( t ) ;
30 }
31 } finally {
32 connection.setAutoCommit( true );
33 }
34 } catch ( SQLException e ) {
35 throw DatabaseException.fromSQLException( null, e );
36 }
37 }
38
39 public abstract Object executeInTransaction( DatabaseConnection connection ) throws DatabaseException;
40
41 }