[英]Using Play Framework Anorm, how do I get the auto-generated id back for an insert?
Suppose I have: 假设我有:
case class SomeModel(
id : Pk[Long],
description : String
)
object SomeModel extends Magic[SomeModel] {
def ayDogAy = {
var aydog = SomeModel(NotAssigned, "aydog")
this.insert(aydog)
}
}
How do I get back the inserted id of aydog? 如何找回插入的aydog ID?
If it matters, my backing database is Postgres 如果重要的话,我的支持数据库是Postgres
在播放2中,如果您具有自动递增的长PK:
val id: Long = SQL("insert into bla bla bla").on("bleh", "blah").executeInsert().get
I don't use the Magic trait (as it is removed in Play 2.0), so I'm not sure if this works here too. 我不使用Magic特性(因为在Play 2.0中已将其删除),所以我不确定这是否也适用。 In SQL you can use SCOPE_IDENTITY() to get the last id used on the connection.
在SQL中,您可以使用SCOPE_IDENTITY()获取该连接上使用的最后一个ID。 So you can do somehing like
所以你可以做一些像
val id = SQL("SELECT SCOPE_IDENTITY()")().collect {
case Row(id: Int) => id
}.head
new SomeModel(new Id(id), "aydog")
I'm just playing around with Play right now. 我现在正在玩Play。 So this is nothing I'd recommend using in production without further investigations.
因此,我建议您在没有进一步调查的情况下将其用于生产。 I'm especially unsure if there might be concurrency issues, when several threads use the ayDogAy method.
当多个线程使用ayDogAy方法时,我尤其不确定是否可能存在并发问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.