Anorm中的原子MySQL事务

Art*_*hur 5 mysql scala anorm

我写了一个简单的点击计数器,它使用Anorm更新MySQL数据库表.我希望事务是原子的.我认为最好的方法是将所有SQL字符串连接在一起并进行一次查询,但这似乎不可能与Anorm一起使用.相反,我已将每个选择,更新和提交放在单独的行上.这有效,但我不禁想到他们必须是一个更好的方法.

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()
  }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以看到更好的方法吗?

ser*_*jja 10

使用withTransaction而不是withConnection像这样:

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()
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么你甚至会在这里使用交易?这也应该有效:

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()
  }
}
Run Code Online (Sandbox Code Playgroud)