Frage

I have a table with autoid for the id field. After inserting a row with anorm I'd like to retrieve the generated id. Any idea?

 SQL(
    """
      insert into accom (id,places,lat,lon,permaname,country,defaultLanguage) values (
         {places}, {lat}, {lon}, {permaname}, {country}, {defaultLanguage}
      )
    """).on(
      'id -> id,
      'places -> places,
      'lat -> lat,
      'lon -> lon,
      'permaname -> permaname,
      'country -> country,
      'defaultLanguage -> defaultLanguage).executeUpdate()
}
War es hilfreich?

Lösung

In the latest version you need a scalar:

   val newId = SQL(
      """
      insert into accom (places,lat,lon,permaname,country,defaultLanguage) 
      values ({places}, {lat}, {lon}, {permaname}, {country}, {defaultLanguage})
      """).on(
        'places -> places,
        'lat -> lat,
        'lon -> lon,
        'permaname -> permaname,
        'country -> country,
        'defaultLanguage -> defaultLanguage).executeInsert(scalar[Long].single)  

Andere Tipps

Use executeInsert instead of executeUpdate, and the return value is the id.

Use the executeInsert method instead of executeUpdate; it returns an Option[T] where T is the type of the primary key.

You might want to take a look at How to Retrieve the Primary Key When Saving a New Object in Anorm which also shows you how to formulate your INSERT statement without specifying the id — which you want to have generated.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top