Question

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

Was it helpful?

Solution

In Play 2 if you have an autoincrement long PK:

val id: Long = SQL("insert into bla bla bla").on("bleh", "blah").executeInsert().get

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top