Reputation: 21
Is there any @transactional anotation to execute a query ?
object UserRepository {
fun getAll() : List<User> {
return User.selectAll().map { User } // how to add it in a transaction ? // Is it the right way to map query to a Class ?
}
fun get(id: Int) : User? {
return User.select { User.id eq id id}.map { User.it } // Mapping Not working
}
Upvotes: 2
Views: 8710
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
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
Reputation: 7236
Mapping should be done automatically. See the documentation:
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