从案例类表单中的Slick 2.0查询中获取值

时间:2014-11-27 16:53:22

标签: scala slick-2.0

我试图从Scala Slick查询中获取基础查询案例类,对我来说似乎比应该更难。这是我的编译器错误:

[info] Compiling 18 Scala sources to /home/target/scala-2.11/classes... [error] /home/src/main/scala/com/core/address/AddressDAO.scala:30: type mismatch; [error] found : scala.slick.lifted.Query[com.core.address.AddressDAO,com.core.protocol.Address,Seq] [error] required: Option[com.core.protocol.Address] [error] q

这是我写的方法:

  def getAddress(otherAddress: String): Future[Option[Address]] = {
    future {
      val q = for (addr <- addresses if (addr.address == otherAddress)) yield addr
      q
    }

这是Slick Schema:

class AddressDAO(tag: Tag) extends Table[Address](tag, "ADDRESSES") with DbConfig {

  def address = column[String]("ADDRESS", O.PrimaryKey)
  def hash160 = column[String]("HASH160")
  def n_tx = column[Long]("N_TX")
  def total_received = column[Double]("TOTAL_RECEIVED")
  def total_sent = column[Double]("TOTAL_SENT")
  def final_balance = column[Double]("FINAL_BALANCE")
  def * = (hash160, address, n_tx, total_received, total_sent, final_balance) <> (Address.tupled, Address.unapply)

}

我想要做的是在方法getAddress的返回类型中表达,即Future[Option[Address]]。我想要数据库找到的第一个元素。实际返回的类型是scala.slick.lifted.Query[com.core.address.AddressDAO,com.core.protocol.Address,Seq]

类型

似乎没有任何execute方法或任何东西可以启动查询。我怀疑这可以用for-comprehensions完成,但我无法弄清楚如何实际做到这一点。

谢谢!

2 个答案:

答案 0 :(得分:1)

您必须实际运行查询。

q.firstOption是您可能想要使用的:

def getAddress(otherAddress: String): Future[Option[Address]] = {
    future {
      val q = for (addr <- addresses if (addr.address == otherAddress)) yield addr
      q.firstOption
    }

PS。简单地过滤给定地址值的地址确实更简洁。当然,此查询的性能取决于您是否在该字段上有索引以及表的大小:)

答案 1 :(得分:1)

我当然不是Slick的专家,但在快速阅读docs之后,我想知道是否可能在Future中包含这样的内容会起作用:

addresses.filter(_.address === "givenAddressString").firstOption