将Slick 2.1 StaticQuery迁移到Slick 3.1

时间:2018-10-24 18:18:55

标签: scala upgrade slick slick-3.0

我正在尝试在Play应用程序中将一些代码从Slick 2.1迁移到Slick 3.1,DBIO Actions上的文档完全使我头疼。而且,我很难在网上找到任何地方的示例,这些示例说明了如何将StaticQuery的使用迁移到Slick 3.1。这是我在Slick 2.1中使用的代码:

import scala.slick.jdbc.{GetResult, StaticQuery => Q}
...
object RegionTable {
  ...
  def selectSomething(param1: Double, param2: Double): List[Region] = db.withSession { implicit session =>
    val selectSomethingQuery = Q.query[(Double, Double), Region](
      """SELECT ...""".stripMargin
    )
    selectSomethingQuery((param1, param2)).list
  }
}

链接到完整代码:

https://github.com/ProjectSidewalk/SidewalkWebpage/blob/master/app/models/region/RegionTable.scala

类似的问题:

How to use StaticQuery in Slick 3.0.0?

How to port Slick 2.1 plain SQL queries to Slick 3.0

文档和有用的博客文章

http://slick.lightbend.com/doc/3.0.0/upgrade.html

http://slick.lightbend.com/doc/3.1.1/upgrade.html

http://slick.lightbend.com/doc/3.1.1/dbio.html

https://grokbase.com/t/gg/scalaquery/15250knfya/slick-3-removes-withsession-dont-get-caught-by-surprise

1 个答案:

答案 0 :(得分:1)

例如,您具有案例类Region

case class Region(id: Int, name: String, code: String)

第一步,您需要通过提供GetResult隐式对话来告诉slick如何将sql结果映射到您的案例类:

implicit val regionGetResult = GetResult(r => Region(r.nextInt, r.nextString, r.nextString))

比您应该构造DBIOAction:

val selectAction = sql"""select * from regions where name = ${param1} and code = ${param2}""".as[Region]

这将返回您DBIO[Seq[Region]]。现在,您可以使用db对象执行此操作,并得到Future[Seq[Region]]作为结果:

db.run(selectAction).map(regions => ...)