JetBrains Exposed 在尝试访问 select 查询的第一行时抛出错误

JetBrains Exposed throwing an error when trying to access first row of select query

当试图从我的 transaction 中获取第一行时,我收到一个错误:

java.lang.IllegalStateException: No transaction in context.

我的代码如下所示:

fun loadPlayer(client: Client): PlayerLoadResult {
    var player = transaction {
        PlayerModel.select {
            PlayerModel.username eq client.loginUsername
        }
    }.firstOrNull() ?: return PlayerLoadResult.NEW_ACCOUNT

    // ...

    return PlayerLoadResult.LOAD_ACCOUNT
}

我的 PlayerModel 看起来像这样:

object PlayerModel : Table("Players") {
    val id = integer("id").autoIncrement().primaryKey()
    val username = varchar("username", 60).uniqueIndex()
    val displayName = varchar("display_name", 60).uniqueIndex()
    val x = integer("position_x")
    val height = integer("position_y")
    val z = integer("position_z")
    val privilege = integer("privilege").default(1)
    val runEnergy = float("run_energy").default(100.toFloat())
    val displayMode = integer("display_mode").default(0)
    val hash = varchar("password_hash", 60)
    val xteaKeyOne = integer("xtea_one")
    val xteaKeyTwo = integer("xtea_two")
    val xteaKeyThree = integer("xtea_three")
    val xteaKeyFour = integer("xtea_four")
}

我的完整堆栈跟踪如下所示:

java.lang.IllegalStateException: No transaction in context.
    at org.jetbrains.exposed.sql.transactions.TransactionManager$Companion.current(TransactionApi.kt:89) ~[exposed-0.13.6.jar:?]
    at org.jetbrains.exposed.sql.Query.getTransaction(Query.kt:93) ~[exposed-0.13.6.jar:?]
    at org.jetbrains.exposed.sql.Query.flushEntities(Query.kt:299) ~[exposed-0.13.6.jar:?]
    at org.jetbrains.exposed.sql.Query.iterator(Query.kt:303) ~[exposed-0.13.6.jar:?]
    at kotlin.collections.CollectionsKt___CollectionsKt.firstOrNull(_Collections.kt:219) ~[kotlin-stdlib-1.3.21.jar:1.3.21-release-158 (1.3.21)]
    at gg.rsmod.plugins.service.sql.controllers.PlayerLoadController.loadPlayer(PlayerLoadController.kt:38) ~[plugins-0.0.4.jar:?]
    at gg.rsmod.plugins.service.sql.SQLService.loadClientData(SQLService.kt:104) ~[plugins-0.0.4.jar:?]
    at gg.rsmod.game.service.login.LoginWorker.run(LoginWorker.kt:28) [main/:?]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_211]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_211]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_211]

获取第一行似乎有什么问题?此查询应该只 return 一行,而不是多行。

对于未来的观众,只需将 firstOrNull() 移动到 transaction 块范围内即可在评论中解决此问题。

fun loadPlayer(client: Client): PlayerLoadResult {
    var player = transaction {
        PlayerModel.select {
            PlayerModel.username eq client.loginUsername
        }.firstOrNull() ?: return PlayerLoadResult.NEW_ACCOUNT
    }

    // ...

    return PlayerLoadResult.LOAD_ACCOUNT
}