Last Insert ID
Reads database-generated identity IDs from insert results.
Use cases
Use .withId() when one insert should return the database-generated identity primary key.
User.kt
import com.kotlinorm.annotations.PrimaryKey
import com.kotlinorm.interfaces.KPojo
data class User(
@PrimaryKey(identity = true)
var id: Long? = null,
var name: String? = null
) : KPojo
lastInsertIdis available when the inserted KPojo uses@PrimaryKey(identity = true)and the primary key value is leftnull.
Read lastInsertId
Call .withId() on the insert that needs the generated ID.
kotlin
val result = User(name = "Kronos")
.insert()
.withId()
.execute()
val affectedRows = result.affectedRows
val lastInsertId = result.lastInsertIdexecute() returns KronosOperationResult. affectedRows is the number of inserted rows, and lastInsertId is the generated identity value returned by the wrapper or the internal dialect fallback.
When no ID is returned
Kronos does not request a generated ID unless .withId() is present.
kotlin
val result = User(name = "Kronos")
.insert()
.execute()
val lastInsertId = result.lastInsertId // nullIf the primary key value is already set, the insert uses that value and lastInsertId stays empty.
kotlin
val result = User(id = 1001, name = "Kronos")
.insert()
.withId()
.execute()
val lastInsertId = result.lastInsertId // nullDialect fallback SQL
The built-in KronosJdbcWrapper first reads JDBC generated keys during insert execution. If a wrapper cannot provide generated keys directly, Kronos uses the active dialect's follow-up SQL.
Mysql
SELECT LAST_INSERT_ID()PostgreSQL
SELECT LASTVAL()SQLite
SELECT last_insert_rowid()SQLServer
SELECT SCOPE_IDENTITY()Oracle
SELECT MAX("ID") FROM "USER"