MySQL Atomic Transactions in Anorm

I wrote a simple hit counter that updates the MySQL database table using Anorm. I want the transaction to be atomic. I think the best way would be to combine all the SQL rows together and make a single query, but this is not possible with Anorm. Instead, I placed each selection, update, and commit on separate lines. It works, but I can't help but think that they should be better.

private def incrementHitCounter(urlName:String) {
  DB.withConnection { implicit connection =>
    SQL("start transaction;").executeUpdate()
    SQL("select @hits:=hits from content_url_name where url_name={urlName};").on("urlName" -> urlName).apply()
    SQL("update content_url_name set hits = @hits + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
    SQL("commit;").executeUpdate()
  }
}

Can anyone see a better way to do this?

+4
source share
1 answer

Use withTransactioninstead withConnectionas follows:

private def incrementHitCounter(urlName:String) {
  DB.withTransaction { implicit connection =>
    SQL("select @hits:=hits from content_url_name where url_name={urlName};").on("urlName" -> urlName).apply()
    SQL("update content_url_name set hits = @hits + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
  }
}

And why do you even need to use a transaction? This should also work:

private def incrementHitCounter(urlName:String) {
  DB.withConnection { implicit connection =>
    SQL("update content_url_name set hits = (select hits from content_url_name where url_name={urlName}) + 1 where url_name={urlName};").on("urlName" -> urlName).executeUpdate()
  }
}
+7

Source: https://habr.com/ru/post/1531981/


All Articles