18

我正在使用 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()
    }
  }

}

尝试对其进行扩展,我想检索刚刚创建的主键并将其存储在案例类中。

如何检索主键?

4

1 回答 1

35

使用executeInsert方法而不是executeUpdate. 注意这里,前面的方法返回Option[T]whereT是主键的类型。

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

    DB.withConnection { implicit connection =>
        SQL(...).executeInsert()
    } match {
        case Some(long) => long // The Primary Key
        case None       => ...
    }
于 2012-03-25T11:17:26.720 回答