kotlin - 更改 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 列来自哪里?
谢谢。
解决方案
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) }
}
如果您使用uuid
column 作为主键,那么您可以将其从声明中删除并uuid
作为 id 列的名称提供,例如:
object Countries : UUIDTable("country", "uuid") {
val name: Column<String> = varchar("name", 255)
val code: Column<String> = varchar("code", 2)
}
推荐阅读
- c#-8.0 - c# 8.0 switch 表达式中的多个案例
- c# - 批量向/从 AAD 组添加/删除用户
- google-search - 我需要在 Google 搜索结果中添加更多预览行
- hadoop3 - hadoop 3.3.1 fs -mkdir 没有这样的文件或目录
- python - 将 Scala neo4j 写入代码转换为 databrick 中的 Pyspark
- c++ - 在文本文件中查找一个单词并在 C++ 中显示该单词的起始位置
- python - python 和 pandas:使用来自一个 df 的 bin 计数从另一个 df 获得类似的 bin 计数,没有共享列
- android - Admob 横幅和智能横幅广告在加载时会填满整个屏幕
- python - pandas.core.series.Series 浮动
- c# - 从 c# 运行 PowerShell 脚本