简体   繁体   中英

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?

If it matters, my backing database is 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. In SQL you can use SCOPE_IDENTITY() to get the last id used on the connection. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM