2

假设我有:

case class SomeModel(
  id : Pk[Long],
  description : String
)

object SomeModel extends Magic[SomeModel] {
  def ayDogAy = {
    var aydog = SomeModel(NotAssigned, "aydog")
    this.insert(aydog)
  }
}

如何取回插入的aydog id?

如果重要的话,我的后备数据库是 Postgres

4

2 回答 2

4

在 Play 2 中,如果您有一个自动增量长 PK:

val id: Long = SQL("insert into bla bla bla").on("bleh", "blah").executeInsert().get
于 2012-06-08T10:11:56.520 回答
1

我不使用 Magic trait(因为它在 Play 2.0 中被删除),所以我不确定这是否也适用于此。在 SQL 中,您可以使用 SCOPE_IDENTITY() 来获取连接上使用的最后一个 ID。所以你可以做一些像

    val id = SQL("SELECT SCOPE_IDENTITY()")().collect {
               case Row(id: Int) => id
             }.head
    new SomeModel(new Id(id), "aydog")

我现在只是在玩 Play。所以我不建议在没有进一步调查的情况下在生产中使用。当多个线程使用 ayDogAy 方法时,我特别不确定是否可能存在并发问题。

于 2012-03-11T17:50:56.490 回答