我正在使用Scala Play!使用Anorm框架将数据模型持久化到数据库。我遵循了示例代码here:
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()
}
}
}
尝试对其进行扩展,我希望检索刚刚创建的主键并将其存储在case类中。
如何检索主键?
发布于 2012-03-25 19:17:27
使用executeInsert
方法而不是executeUpdate
方法。注意到here,foremer方法返回Option[T]
,其中T
是主键的类型。
您可以使用match
语句提取该值:
DB.withConnection { implicit connection =>
SQL(...).executeInsert()
} match {
case Some(long) => long // The Primary Key
case None => ...
}
https://stackoverflow.com/questions/9859700
复制相似问题