lee*_*nix 6 scala playframework-2.0 slick-3.0
我是Scala,Slick和Play的新手,但我正在尝试使用这项技术做一些小服务.我有一个问题,正确的方法如何检查数据库中项目的存在.
播放动作 - 在浏览器中轻松查看输出:
val id = 5
val name = "xx"
def show(): Action async {
dao.isExist(id,name).map(c => Ok(c.toString)
}
Run Code Online (Sandbox Code Playgroud)
道
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.
Run Code Online (Sandbox Code Playgroud)
我认为我应该避免使用Await,但在这种情况下,我需要根据DB将返回的内容进行一些操作.你能建议解决这个案子的最佳模式吗?
Pat*_*iek 20
首先:如果要转换异步操作的结果,则应该使用Future.map(或者flatMap如果要嵌套异步操作)并将a返回Future给控制器.
除此之外,您的整个方法可以重构为:
def exists(id : Int, name : String) : Future[Boolean] =
db.run(User.filter(i => i.id === id || i.name === name).exists.result)
Run Code Online (Sandbox Code Playgroud)
这应该转化为某些东西,SELECT 1 ... WHERE EXISTS而不是COUNT(*)或更糟糕的是,在您的特定情况下,它将SELECT *与客户端长度检查.