Scala/Slick plain SQL: retrieve multiple results i

2019-06-11 05:22发布

问题:

I have a simple method that retrieves single row from a db table:

object Data {

    implicit val getListStringResult = GetResult[List[Object]] (
        r => (1 to r.numColumns).map(_ => r.nextObject).toList
    )

    def getUser(id: Int): Option[Map[String, Object]] = DB.withSession {
        val columns = MTable.getTables(None, None, None, None).list.filter(_.name.name == "user").head.getColumns.list.map(_.column)    
        sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[Object]].firstOption.map(columns zip _ toMap)
    }

}

How can I modify this method to retrieve multiple rows into a list? The result type should look something like List[Map[String, Object]]

I'm on Play 2.2.1, Slick 1.0.1, Scala 2.10.3, Java 1.8 64bit

回答1:

Just switch out your firstOption to list:

object Data {

  implicit val getListStringResult = GetResult[List[Object]] (
    r => (1 to r.numColumns).map(_ => r.nextObject).toList
  )

  def getUser(id: Int): List[Map[String, Object]] = DB.withSession {
    val columns = MTable.getTables(None, None, None, None).list.filter(_.name.name == "user").head.getColumns.list.map(_.column)
    sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[Object]].list.map(columns zip _ toMap)
  }

}