Scala/Slick plain SQL: retrieve result as a map

2019-02-07 12:28发布

I have a simple method to retrieve a user from a db with Sclick plain SQL method:

object Data {

    implicit val getListStringResult = GetResult[List[String]] (
        prs => (1 to prs.numColumns).map(_ => prs.nextString).toList
    )

    def getUser(id: Int): Option[List[String]] = DB.withSession {
        sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[String]].firstOption
    }

}

The result is List[String] but I would like it to be something like Map[String, String] - column name and value pair map. Is this possible? If so, how?

My stack is Play Framework 2.2.1, Slick 1.0.1, Scala 2.10.3, Java 8 64bit

2条回答
来,给爷笑一个
2楼-- · 2019-02-07 13:00

It's possible to do this without querying the table metadata as follows:

   implicit val resultAsStringMap = GetResult[Map[String,String]] ( prs => 
      (1 to prs.numColumns).map(_ => 
         prs.rs.getMetaData.getColumnName(prs.currentPos+1) -> prs.nextString
      ).toMap
   )

It's also possible to build a Map[String,Any] in the same way but that's obviously more complicated.

查看更多
做自己的国王
3楼-- · 2019-02-07 13:12
import scala.slick.jdbc.meta._
val columns = MTable.getTables(None, None, None, None)
                    .list.filter(_.name.name == "USER") // <- upper case table name
                    .head.getColumns.list.map(_.column)
val user = sql"""SELECT * FROM "user" WHERE "id" = $id""".as[List[String]].firstOption
                                                         .map( columns zip _ toMap )
查看更多
登录 后发表回答