Michael Scofield
Michael Scofield

Reputation: 138

String primary key with Jetbrains' Exposed library - Kotlin

I'm having problems figuring out how to write a table with a string primary key and have an Entity of the table too. Whether I put IdTable<String> as the Table type or try to use it with a plain Table nothing works.

Upvotes: 4

Views: 4607

Answers (1)

Vlad K
Vlad K

Reputation: 421

In case you really need to have String as a primary key, here you go:

/*
 * 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) {
    // ...
}

Upvotes: 12

Related Questions