2
  • 如何将选择查询映射到类
  • 是否有任何@transactional 注释来执行查询?

    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
    }
    
4

3 回答 3

4

我知道已经晚了,但对于其他有这个问题的人来说:如果您使用的是 DSL,您可以在数据类中创建一个函数以用于映射目的。例如 :

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

在您的交易块中:

transaction {
        user = UserTable.select { UserTable.id eq userId }.map { User.fromRow(it) }
    }
于 2020-11-30T14:58:00.387 回答
3

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()
  }
}
于 2018-05-28T10:05:26.223 回答
0

我将值提取到 HashMap 中的解决方案,以 pk 作为值

    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]
                        }
                    }
                }
            }
        }
    }
于 2021-11-06T08:10:42.227 回答