Created
November 19, 2012 17:18
-
-
Save jbrains/4112020 to your computer and use it in GitHub Desktop.
An example of a Template Method that handles "rollback on exception" in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
new RollbackOnExceptionAction(new JtaTransactionService()) | |
.executeInTransaction(new Closure() { | |
@Override | |
public void execute(Object... arguments) { | |
// cast arguments | |
// perform action | |
// throw exception if there's a problem | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RollbackOnExceptionAction implements ExecuteInTransaction { | |
private final TransactionService transactionService; | |
public RollbackOnExceptionAction(TransactionService transactionService) { | |
this.transactionService = transactionService; | |
} | |
@Override | |
public void executeInTransaction(Closure closure) { | |
try { | |
transactionService.beginTransaction(); | |
closure.invoke(); | |
transactionService.commit(); | |
} | |
catch (Exception signalRollback) { | |
transactionService.rollback(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment