Bassirou Rabo
Bassirou Rabo

Reputation: 21

Kotlin exposed DSL Query mapping

Upvotes: 2

Views: 8710

Answers (3)

Sm Smertik
Sm Smertik

Reputation: 1

My solution for extract values into HashMap, with pk as value

    fun getRaw(): List<HashMap<String, Any?>> {
        return transaction {
            val list = Users.selectAll().toList()

            list.map { data ->
                HashMap<String, Any?>().also { map ->
                    Users.columns.forEach {
                        if (data[it] is EntityID<*>) {
                            map[it.name] = (data[it] as EntityID<*>).value
                        } else {
                            map[it.name] = data[it]
                        }
                    }
                }
            }
        }
    }

Upvotes: 0

Ali Zarei
Ali Zarei

Reputation: 3753

I know it's late but for other people who have this question: If you are using DSL, You can create a function in your data class for mapping purposes. for example :

data class User(
    val id: Int,
    val username: String,
    val password: String
) {

    companion object {

        fun fromRow(resultRow: ResultRow) = User(
            id = resultRow[UserTable.id].value,
            username= resultRow[UserTable.username],
            password = resultRow[UserTable.password]
        )
    }
}

and in your transaction block :

transaction {
        user = UserTable.select { UserTable.id eq userId }.map { User.fromRow(it) }
    }

Upvotes: 5

zoku
zoku

Reputation: 7236

Mapping should be done automatically. See the documentation:

Documentation on DAO

Documentation on DSL

Documentation on transactions

Table:

object Users : IntIdTable() {
  val name = varchar("name", 50)
}

Entity:

class User(id: EntityID<Int>) : IntEntity(id) {
  companion object : IntEntityClass<User>(Users)

  var name     by Users.name
}

Usage:

fun getAllUsers(): List<User> {
  Database.connect(/* ... */)
  return transaction {
    User.all().toList()
  }
}

Upvotes: 3

Related Questions