Scala/Slick plain SQL: retrieve multiple results into list of maps

守給你的承諾、 提交于 2019-12-10 12:13:20

问题


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)
  }

}


来源:https://stackoverflow.com/questions/19894465/scala-slick-plain-sql-retrieve-multiple-results-into-list-of-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!