Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala anorm retrieve inserted id

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()
}
like image 574
Jordi P.S. Avatar asked Dec 20 '22 09:12

Jordi P.S.


2 Answers

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)  
like image 190
Jordi P.S. Avatar answered Dec 29 '22 13:12

Jordi P.S.


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

like image 31
Eve Freeman Avatar answered Dec 29 '22 15:12

Eve Freeman