【问题标题】:Check if element exists in database using Slick 3 and Play使用 Slick 3 和 Play 检查数据库中是否存在元素
【发布时间】:2015-11-10 10:33:21
【问题描述】:

我是 Scala、Slick 和 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,但在这种情况下,我需要根据 DB 将返回的内容采取一些措施。您能否建议解决这种情况的最佳模式是什么?

【问题讨论】:

  • 查看Essential Slick。这本书涵盖了 Slick 2 和 3。我用它来提升 Slick - 编写良好且可靠的示例。
  • 谢谢。示例看起来非常有用且很有帮助

标签: scala playframework-2.0 slick-3.0


【解决方案1】:

首先:如果你想转换异步操作的结果,你应该使用Future.map(或者如果你想嵌套异步操作,则使用flatMap)并返回一个Future给控制器。

除此之外,您的整个方法可以重构为:

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 *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-20
    相关资源
    最近更新 更多