Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the conventional way to handle a transaction in Play 2 Scala?

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 DbActions instead of regular Actions. 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

like image 452
Todd O'Bryan Avatar asked Nov 02 '22 20:11

Todd O'Bryan


1 Answers

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)
}
like image 144
ndeverge Avatar answered Nov 15 '22 05:11

ndeverge