首页 > 解决方案 > 更改 Exposed ORM 中的 ID 名称

问题描述

我在 Kotlin 中定义了一个表和一行:

    object Countries : UUIDTable("country") {
        val uuid: Column<UUID> = uuid("uuid").autoGenerate()
        val name: Column<String> = varchar("name", 255)
        val code: Column<String> = varchar("code", 2)
        override val primaryKey = PrimaryKey(uuid, name = "country_pk")
    }

    class Country(uuid: EntityID<UUID>) : UUIDEntity(uuid) {
        companion object : UUIDEntityClass<Country>(Countries)
        var uuid by Countries.uuid
        var name by Countries.name
        var code by Countries.code
    }

如您所见,我使用列名为“uuid”的 UUID 作为我的主键。

当我进行选择时:

var country = Country.find { Countries.code eq "GB" }.first()

查询失败并出现以下错误:

org.jetbrains.exposed.exceptions.ExposedSQLException: org.postgresql.util.PSQLException: ERROR: column country.id does not exist

原因很简单。生成的 SQL 查询如下所示:

SELECT country.id, country.uuid, country."name", country.code FROM country WHERE country.code = ?

所以我现在的问题是:ID 列来自哪里?

谢谢。

标签: kotlinormkotlin-exposed

解决方案


id 列在UUIDTable类中声明:

open class UUIDTable(name: String = "", columnName: String = "id") : IdTable<UUID>(name) {
    override val id: Column<EntityID<UUID>> = uuid(columnName)
            .autoGenerate()
            .entityId()
    override val primaryKey by lazy { super.primaryKey ?: PrimaryKey(id) }
}

如果您使用uuidcolumn 作为主键,那么您可以将其从声明中删除并uuid作为 id 列的名称提供,例如:

object Countries : UUIDTable("country", "uuid") {
    val name: Column<String> = varchar("name", 255)
    val code: Column<String> = varchar("code", 2)
}

推荐阅读