公开选择返回类型



我是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])
}

也请查看维基。

最新更新