Setting up transactions properly can be complicated. I've seen cases
where it was done wrong. Even when it's done right, it adds a lot of
client code that gets repeated every time a transaction is used. I have
an idea to make transaction handling easier and more reliable:
1. Create an interface:
public interface TransactionTask {
void run() throws GenericEntityException;
}
2. Add a method to TransactionUtil.java:
public static void runTransactionTask(TransactionTask task, boolean
suspendCurrent) throws GenericEntityException, GenericTransactionException {
...
}
The TransactionUtil.runTransactionTask method will contain all of the
correct begin, suspend, commit, resume, rollback, try, catch, finally
logic. All the client code needs to do is put the transaction-protected
code in a TransactionTask instance run() method and call the
TransactionUtil.runTransactionTask method. Bottom line - less code,
better results.
Example:
TransactionTask task = new TransactionTask() {
public void run() throws GenericEntityException {
GenericValue target = delegator...;
target.set("someField", "someValue");
target.store();
}
};
TransactionUtil.runTransactionTask(task, true);
What do you think?
-Adrian