我是ktor和Exposed的新手。 我想编写一个按id
返回Category
对象的函数
这是我的数据类
@Serializable
data class Category(
val id: Long,
val name: String,
val count: Int
)
这是我的main
函数
fun main() {
embeddedServer(
factory = CIO,
port = 8080,
host = "0.0.0.0",
module = {
install(ContentNegotiation) {
json()
}
configureDependencyInjection()
configureCategoryRouting()
configureImageRouting()
Database.connect(
url = "jdbc:postgresql://localhost:5432/postgres",
driver = "org.postgresql.Driver",
user = "postgres",
password = "74279744fz"
)
这是我的函数,应该返回一个Category
fun getCategoryById(id: Long): Category {
val category = transaction {
Categories.select {
Categories.id eq id
}
}
return category
}
但是返回的category
不是Category
而是Query
类。
如何将其转换为Category
您必须将ResultRow
中的值映射到Category
数据类中。 喜欢:
Categories.select {
Categories.id eq id
}.map { row ->
Category(row[Categories.id], row[Categories.name], row[Categories.count])
}
也请查看维基。