如何在Anorm中保存新对象时检索主键

Jac*_*ter 18 sql scala playframework anorm playframework-2.0

我正在使用Scala Play!使用Anorm将数据模型持久化到数据库的框架.我在这里遵循示例代码:

case class Bar(id: Pk[Long], name: String)

object Bar {

  val simple = {
    get[Pk[Long]]("id") ~
    get[String]("name") map {
      case id~name => Bar(id, name)
    }
  }

  def findAll(): Seq[Bar] = {
    DB.withConnection { implicit connection =>
      SQL("select * from bar").as(Bar.simple *)
    }
  }

  def create(bar: Bar): Unit = {
    DB.withConnection { implicit connection =>
      SQL("insert into bar(name) values ({name})").on(
        'name -> bar.name
      ).executeUpdate()
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

试图扩展它,我想检索刚刚创建的主键并将其存储在案例类中.

如何检索主键?

Jac*_*ter 35

使用该executeInsert方法代替executeUpdate.注意这里,所述foremer方法返回Option[T]其中T是主键的类型.

您可以使用match语句提取值:

    DB.withConnection { implicit connection =>
        SQL(...).executeInsert()
    } match {
        case Some(long) => long // The Primary Key
        case None       => ...
    }
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于主键是自动增量键的情况.如果不是,结果将为None (3认同)
  • 或者只是`.executeInsert(标量[长]单)`没有'匹配' (3认同)