Boolean result = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Boolean>() {
public Boolean execute() throws Throwable {
//Your code
return true;
}
}, false, true);
This is quite a bit of code and gets ugly if you start embedding a bunch of code inside this block. It is also not very testable with out some crazy mocking.
Groovy Closures to the rescue. http://groovy.codehaus.org/Closures
I created a simple TransactionHelper Groovy class with a method that takes a closure and wraps the closure inside of the above code required for a transaction and wired it as a Spring Bean.
import org.alfresco.repo.transaction.RetryingTransactionHelper
import org.alfresco.service.transaction.TransactionService
class TransactionHelper {
private TransactionService transactionService
def executeInSperarateTransaction(closure) {
Boolean result = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Boolean>() {
public Boolean execute() throws Throwable {
closure()
return true
}
}, false, true)
}
void setTransactionService(TransactionService transactionService) {
this.transactionService = transactionService
}
}
Now if I need to execute a transaction I can simply do the following.
transactionHelper.executeInSperarateTransaction({ nodeService.addAspect(nodeRef, MyModel.THUMBNAIL_ASPECT, new HashMap<QName, Serializable>())})
You can simply pass a closure
statement like above or pass in a closure like the following.
def
closure
() {
def localVariable = new java.util.Date()
return { println localVariable }
}
transactionHelper.executeInSeperateTransaction(closure)
For more information on Groovy and Closures see
http://groovy.codehaus.org/Closures
No comments:
Post a Comment