I'm using JDO for data storage in a Play 2.1 Scala project. Ideally, I'd like each request to have its own transaction, committing when it's finished, and rolling back if something goes wrong.
The best way I can figure out to do this is with Action Composition, where I create my own Action
-like object that starts the transaction, wraps the block of code in an Action
, evaluates it and saves the result, commits or rolls back the transaction, and then returns the result.
The only thing that concerns me about this is that my whole project now consists of DbAction
s instead of regular Action
s. I'm not sure why this concerns me, except that I think there must be a better place to do this. However, when I check the hooks available in GlobalSettings
, nothing looks like it would work.
Should I just go with DbAction
and stop second-guessing myself, or is there a place to hook this behavior in so that I can just use Action
?
Todd
I don't if it is a better alternative, but you could also use Action Composition instead of creating a subclass via inheritance.
Basically, you could write something like this:
def TransactionalAction(f: Request[AnyContent] => Result): Action[AnyContent] = {
Action { request =>
startTransaction
try {
f(request)
commit
} catch {
case e: Exception => rollback
}
}
}
and then use:
def index = TransactionalAction { request =>
val something = someQueriesInDB
Ok(something)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With