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?
source
share