Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SELECT single record #1111

Closed
alizarei95 opened this issue Dec 4, 2020 · 1 comment
Closed

SELECT single record #1111

alizarei95 opened this issue Dec 4, 2020 · 1 comment

Comments

@alizarei95
Copy link

alizarei95 commented Dec 4, 2020

Hey guys, 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
}

It is not duplicate issue , I have not found any solution in issues

@hfazai
Copy link
Contributor

hfazai commented Dec 4, 2020

You can use single() method:

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 omit the user variable

fun getUser(userId: Int): User = 
        transaction {
                UserTable.select { UserTable.id eq userId }.limit(1).single().let { User.fromRow(it) }
        }

@Tapac Tapac closed this as completed Jan 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants