使用 Jetbrains 公开库的字符串主键 - Kotlin

Mic*_*eld 4 kotlin kotlin-exposed

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

小智 11

如果您确实需要将 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) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)