首页 > 解决方案 > 带有 Jetbrains 的 Exposed 库的字符串主键 - Kotlin

问题描述

我在弄清楚如何使用字符串主键编写表并拥有表的实体时遇到问题。无论我IdTable<String>是作为 Table 类型还是尝试将它与普通的类型一起使用Table都不起作用。

标签: kotlinkotlin-exposed

解决方案


如果您确实需要将 String 作为主键,请执行以下操作:

/*
 * Base class for entities with string id
 */
abstract class StringEntityClass<out E: Entity<String>>(table: IdTable<String>, entityType: Class<E>? = null) : EntityClass<String, E>(table, entityType)

/*
 * Base class for table objects with string id
 */
open class StringIdTable(name: String = "", columnName: String = "id", columnLength: Int = 10) : IdTable<String>(name) {
    override val id: Column<EntityID<String>> = varchar(columnName, columnLength).entityId()
    override val primaryKey by lazy { super.primaryKey ?: PrimaryKey(id) }
}

// Sample usage    

object MyTableWithStringId : StringIdTable() {
    // ...
}

class MyEntityWithStringId(id: EntityID<String>) : Entity<String>(id) {
    // ...
}

推荐阅读