-
-
Save julienba/4031928 to your computer and use it in GitHub Desktop.
One way to do transactions in Play with Anorm
This file contains 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 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