Created
August 31, 2014 14:04
-
-
Save fairjm/99ce55160d4a4adf350b to your computer and use it in GitHub Desktop.
slick2_mysql_for_update
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
package jdbctest | |
import org.scalatest.FlatSpec | |
import org.scalatest.Matchers | |
import model.Tables | |
import model.Tables.UserRow | |
import scala.concurrent.Future | |
import scala.concurrent.Await | |
class JDBCTestSpec2 extends FlatSpec with Matchers { | |
def mysqlDB = { | |
import scala.slick.driver.MySQLDriver.simple._ | |
Database.forURL(url = "jdbc:mysql://localhost:3306/test", | |
user = "root", | |
password = "", | |
prop = null, | |
driver = "com.mysql.jdbc.Driver") | |
} | |
"transcation" should "lock a row(mysql)" in { | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.concurrent.duration._ | |
import scala.slick.driver.MySQLDriver.simple._ | |
import scala.slick.jdbc.{ GetResult, StaticQuery => Q } | |
val f1 = Future { | |
mysqlDB.withTransaction { | |
implicit session => | |
println("one===========query begin") | |
val query = Tables.User.filter(_.id === 2).map(_.name) | |
val name:String = Q.queryNA[String](query.selectStatement + " FOR UPDATE").first | |
println("one==========" + name) | |
Thread.sleep(3000) | |
println("one update change to x-f1") | |
val q2 = Tables.User.filter(_.id === 2).map(_.name) | |
println(q2.updateStatement + " name:" + name) | |
q2.update(name + "-f1") | |
println("one============" + Tables.User.filter(_.id === 2).run.toList(0)) | |
println("one============query end") | |
} | |
} | |
val f2 = Future { | |
mysqlDB.withTransaction { | |
implicit session => | |
println("two===========query begin") | |
val query = Tables.User.filter(_.id === 2).map(_.name) | |
//perform a lock | |
val name = Q.queryNA[String](query.selectStatement + " FOR UPDATE").first | |
println("two===========" + name) | |
Thread.sleep(2800) | |
println("two update change to x-f2") | |
Tables.User.filter(_.id === 2).map(_.name).update(name + "-f2") | |
println("two============" + Tables.User.filter(_.id === 2).run.toList(0)) | |
println("two============query end") | |
} | |
} | |
Await.result(f1, 10.seconds) | |
Await.result(f2, 10.seconds) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment