is there any way to select only one record with kotlin exposed? Currently I'm using below code to select a user from DB, but is there any function like selectSingle() to get an object (not list) ?
fun getUser(userId: Int): User? {
var user: User? = null
transaction {
user = UserTable.select { UserTable.id eq userId }.limit(1).map { User.fromRow(it) }[0]
}
return user
}
I found a good solution for this. Credits goes to hfazai
fun getUser(userId: Int): User? {
var user: User? = null
val user = transaction {
user = UserTable.select { UserTable.id eq userId }.limit(1).single().let { User.fromRow(it) }
}
return user
}
PS : single() will throw NoSuchElementException if there is no result and IllegalArgumentException if there is more than one resulted row.
also you can ommit the user variable
fun getUser(userId: Int): User =
transaction {
UserTable.select { UserTable.id eq userId }.limit(1).single().let { User.fromRow(it) }
}