Reputation: 4018
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()
}
Upvotes: 4
Views: 2354
Reputation: 4018
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)
Upvotes: 7
Reputation: 3114
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.
Upvotes: 2
Reputation: 33175
Use executeInsert
instead of executeUpdate
, and the return value is the id.
Upvotes: 2