0

I insert a new row into a database and its id is auto-incremented ("serial"). How can I get the value of the id after insertion? Currently, I am using the following workaround:

inTransaction {
  Schema.table.insert(new Entry(
      content = "..."
  ))
  def entries = from(Schema.table)(e => select(e) orderBy(e.id desc)).page(0, 1)
  val id = entries.headOption match {
    case Some(entry) => entry.id
    case None => 0
  }
}

If there is no easier way, how can I ensure this entire block will be an atomic operation?

ideaboxer
  • 3,863
  • 8
  • 43
  • 62

1 Answers1

0

yes,

val new = Schema.table.insert(myOriginalOld)
Console println new.id
VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62
  • How would this work, `myOriginalOld` does not have the `id` member and `new` must be of the same type as `myOriginalOld`. If `myOriginalOld` was provided with `id`, I would have to use `on(entries)(entry => declare(entry.id is(autoIncremented("Entry_id_seq"))))` which causes an `ExceptionInInitializerError` on my machine. Otherwise it would not work either... – ideaboxer Apr 08 '13 at 22:15
  • You can use KeyedEntity. For example, if you want the simplest Primary Key in your database, use smth like `case class Fuit(id: Long = 0L, color: String) extends KeyedEntity[Long]` In your question you said that you want the id from the database. If so, the squeryl object MUST contain the id. – VasiliNovikov Apr 08 '13 at 22:23