4

当尝试从 my 获取第一行时transaction,我收到一个错误:

java.lang.IllegalStateException:上下文中没有事务。

我的代码如下所示:

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]

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

4

1 回答 1

1

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
}
于 2022-01-05T15:25:36.207 回答