Created
September 25, 2012 19:21
-
-
Save bmc/3783883 to your computer and use it in GitHub Desktop.
One way to do transactions in Play with Anorm
This file contains hidden or 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
case class Article(...); | |
object Article { | |
import DBUtil._ | |
def delete(id: Long): Either[String, Boolean] = { | |
withTransaction { implicit connection => | |
SQL("DELETE FROM comments WHERE article_id = {id}").on("id" -> id).executeUpdate() | |
SQL("DELETE FROM appusers WHERE id = {id}").on("id" -> id).executeUpdate( ) | |
Right(true) | |
} | |
} | |
} |
This file contains hidden or 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
object DBUtil { | |
def withTransaction[T](code: java.sql.Connection => Either[String,T]): Either[String, T] = { | |
val connection = play.db.DB.getConnection | |
val autoCommit = connection.getAutoCommit | |
try { | |
connection.setAutoCommit(false) | |
result = code(connection) | |
result.fold( | |
{ error => throw new Exception(error) }, | |
{ _ => connection.commit() } | |
) | |
result | |
} | |
catch { | |
case e: Throwable => | |
connection.rollback() | |
val msg = "Error, rolling back transaction: " + e.getMessage | |
Logger.error(msg) | |
Left(msg) | |
} | |
finally { | |
connection.setAutoCommit(autoCommit) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anorm doesn't provide a built-in way to handle database transactions, but the code in
TransactionUtil.scala
, above, appears to get the job done. It assumes the caller will pass a block of code that returnsLeft(errorMessage)
on error andRight(something: T)
on success.Article.scala
shows an example of its use.