【问题标题】:Scala play withSession deprecatedScala 玩 withSession 已弃用
【发布时间】:2016-08-13 05:53:37
【问题描述】:

我正在从 slick 2.1 迁移到 3.0。如您所知,withSession 函数已被弃用。

如何更改以下代码:

def insert(vote: Vote) = DB.withSession { implicit session =>
  insertWithSession(vote)
}
def insertWithSession(vote: Vote)(implicit s: Session) = {
  Votes.insert(vote)
}

Votes.insert 出现编译错误,错误是:

could not find implicit value for parameter s: slick.driver.PostgresDriver.api.Session

最后,除了official link,还有其他文档帮助我迁移吗?我需要更多详细信息。

【问题讨论】:

    标签: postgresql scala playframework slick


    【解决方案1】:

    假设您使用 play-slick 来实现与 play 的巧妙集成。

    您可以查看https://www.playframework.com/documentation/2.5.x/PlaySlick了解更多详情。

    在 build.sbt 中添加 slick 和 jdbc 依赖项

    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-slick" % "2.0.0",
      "com.typesafe.play" %% "play-slick-evolutions" % "2.0.0"
      "org.postgresql" % "postgresql" % "9.4-1206-jdbc4"
    )
    

    在你的 application.conf 中添加 postgres 配置

    slick.dbs.default.driver="slick.driver.PostgresDriver$"
    slick.dbs.default.db.driver="org.postgresql.Driver"
    slick.dbs.default.db.url="jdbc:postgresql://localhost/yourdb?user=postgres&password=postgres"
    

    现在像下面这样定义你的模型,

    package yourproject.models
    
    import play.api.db.slick.DatabaseConfigProvider
    import slick.driver.JdbcProfile
    
    case class Vote(subject: String, number: Int)
    
    class VoteTable(tag: Tag) extends Table[Vote](tag, "votes") {
      def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
      def subject = column[String]("subject")
      def number = column[Int]("number")
    
      def * = (id.?, subject, number) <> (Vote.tupled, Vote.unapply)
    }
    
    class VoteRepo @Inject()()(protected val dbConfigProvider: DatabaseConfigProvider) {
      val dbConfig = dbConfigProvider.get[JdbcProfile]
      val db = dbConfig.db
      import dbConfig.driver.api._
    
      val Votes = TableQuery[VoteTable]
    
      def insert(vote: Vote): DBIO[Long] = {
        Votes returning Votes.map(_.id) += vote
      }
    
    }
    

    现在你的控制器看起来像,

    import javax.inject.Inject
    
    import yourproject.models.{VoteRepo}
    import play.api.libs.concurrent.Execution.Implicits.defaultContext
    import play.api.mvc.{Action, Controller}
    
    class Application @Inject()(voteRepo: VoteRepo) extends Controller {
    
      def createProject(subject: String, number: Int) = Action.async {
        implicit rs => {
          voteRepo.create(Vote(subject, number))
            .map(id => Ok(s"project $id created") )
        }
      }
    
    }
    

    【讨论】:

    • 我必须添加什么才能使用 Postgre 作为我的数据库驱动程序?
    猜你喜欢
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2015-02-17
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多