Search code examples
springkotlinspring-data-r2dbcr2dbc

How to return generated ID with Fluent Data Access API in Spring Data R2DBC


My database automatically generate IDs when new records are inserted, and I want to use the generated ID in my code once the insertion completed. When using Statement, it can be achieved by the following approach.

db.execute("INSERT INTO table (name, state) VALUES(:name, :state)")
    .filter { s, next -> next.execute(s.returnGeneratedValues("id")) }
    .bind("name", name)
    .bind("state", state)
    .map { t -> t.get("id", Long::class.java) }

However, I am using Fluent Data Access API currently, thus an approach to get inserted ID in the following code style will be appreciated in my case.

db.insert().into("table")
    .value("name", name)
    .value("state", state)
    // get generated ID

Is there any solution to achieve so?


Solution

  • You should be able to use the same map method:

    db.insert().into("test")
        .value("name", name)
        .value("state", state)
        // Use "LAST_INSERTED_ID" for MySQL
        .map { t -> t.get("id", java.lang.Long::class.java) }
        .one()
    

    (I'm assuming the generated ID column in the table is called id)