我是 Scala、Slick 和 Play 的新手,但我正在尝试使用这项技术做一些小服务。我对如何检查数据库中项目是否存在的正确方法有疑问。
Play 操作——在浏览器中轻松查看输出:
val id = 5
val name = "xx"
def show(): Action async {
dao.isExist(id,name).map(c => Ok(c.toString)
}
道
User = TableQuery[UserRow]
def isExist(id:Int, name:String) = {
val res = db.run(User.filter(i => (i.id === id || i.name === name)).result)}
// I would like to do something like
if (res.length > 0) true else false
// or since action is async to return future.
res match {
case 0 => Future(true)
case _ => Future(false)
}
// but this doesnt compile. I came up with
val trueRes = Await.result(res, Duratin.Inf)
// which in not async Action do what I want.
我认为我应该避免使用 Await,但在这种情况下,我需要根据数据库将返回的内容采取一些操作。您能否建议解决这种情况的最佳模式是什么?
最佳答案
首先:如果你想转换异步操作的结果,你应该使用 Future.map
(如果你想嵌套异步操作,你应该使用 flatMap
)并且将 Future
返回给 Controller 。
除此之外,您的整个方法可以重构为:
def exists(id : Int, name : String) : Future[Boolean] =
db.run(User.filter(i => i.id === id || i.name === name).exists.result)
应该转换为类似于 SELECT 1 ... WHERE EXISTS
而不是 COUNT(*)
的内容,或者更糟糕的是,在您的特定情况下,它会是 SELECT *
并进行客户端长度检查。
关于scala - 使用 Slick 3 和 Play 检查数据库中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33627971/