Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Retrieve the Primary Key When Saving a New Object in Anorm

I'm using Scala Play! framework with Anorm to persist the data model to the database. I followed the example code here :

case class Bar(id: Pk[Long], name: String)

object Bar {

  val simple = {
    get[Pk[Long]]("id") ~
    get[String]("name") map {
      case id~name => Bar(id, name)
    }
  }

  def findAll(): Seq[Bar] = {
    DB.withConnection { implicit connection =>
      SQL("select * from bar").as(Bar.simple *)
    }
  }

  def create(bar: Bar): Unit = {
    DB.withConnection { implicit connection =>
      SQL("insert into bar(name) values ({name})").on(
        'name -> bar.name
      ).executeUpdate()
    }
  }

}

Trying to expand on it, I want to retrieve the primary key just created and store it in the case class.

How can I retrieve the primary key?

like image 233
Jacob Groundwater Avatar asked Mar 25 '12 11:03

Jacob Groundwater


1 Answers

Use the executeInsert method instead of executeUpdate. Noted here, the foremer method returns Option[T] where T is the type of the primary key.

You can extract the value with a match statement:

    DB.withConnection { implicit connection =>
        SQL(...).executeInsert()
    } match {
        case Some(long) => long // The Primary Key
        case None       => ...
    }
like image 175
Jacob Groundwater Avatar answered Sep 18 '22 18:09

Jacob Groundwater