Question

I'm using Play2 with Anorm. Is there a way to execute an INSERT statement and obtain the automatically generated primary key as a result?

Was it helpful?

Solution

Use the RETURNING clause:

INSERT INTO tbl(foo)
VALUES ('bar')
RETURNING foo_id;

With Anorm it could look like this (I am not an expert with Anorm):

import play.db.anorm._

val firstRow = SQL("INSERT INTO tbl(foo)
                    VALUES ('bar') RETURNING foo_id").apply().head

val foo_id = firstRow[int](“foo_id”)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top