在 Anorm 中保存新对象时如何检索主键 [英] How to Retrieve the Primary Key When Saving a New Object in Anorm
本文介绍了在 Anorm 中保存新对象时如何检索主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Scala Play!使用 Anorm 将数据模型持久化到数据库的框架.我按照示例代码 这里 :
I'm using Scala Play! framework with Anorm to persist the data model to the database. I followed the example code 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()
}
}
}
尝试对其进行扩展,我想检索刚刚创建的主键并将其存储在案例类中.
Trying to expand on it, I want to retrieve the primary key just created and store it in the case class.
如何检索主键?
推荐答案
使用 executeInsert
方法代替 executeUpdate
.注意到这里,前一个方法返回Option[T]
其中 T
是主键的类型.
Use the executeInsert
method instead of executeUpdate
. Noted here, the foremer method returns Option[T]
where T
is the type of the primary key.
您可以使用 match
语句提取值:
You can extract the value with a match
statement:
DB.withConnection { implicit connection =>
SQL(...).executeInsert()
} match {
case Some(long) => long // The Primary Key
case None => ...
}
这篇关于在 Anorm 中保存新对象时如何检索主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文