Pstr
Pstr

Reputation: 857

Entity referencedOn using foreign key instead of Entity ID

So I'm using Kotlin Exposed DAO API. let's say I have in my structure an id that I use internally and another that I would export to obfuscate which record is which, still having the from:to relationship in my database.

So I have my entities:

UserEntity(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<UserEntity>(TransactionTable)

    var externalId by UserTable.external_id
    var name by UserTable.name
    

TransactionEntity(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<TransactionEntity>(TransactionTable)

    var userId by TransactionTable.user_id
    var value by TransactionTable.value

    //relationships
    var user by UserEntity referencedOn TransactionTable.user_id

and my transaction table

object TransactionTable: IntIdTable("transaction_1"){
    var user_id = integer("user_id").references(UserTable.external_id)
    var value= double("value")

The problem here is that even when my FK is referencing external_id, the entity will look for the IDs of the UserEntity, so I'll have an IllegalStateException telling me that there is no such User with id = "my_extenal_id"...

Can I reference my Entity's relationship to join using the FK, or even explicitly say which field I want it to use for the join, without using the DSL API?

I know I can fix that with DSL API, but I would like to keep using my DAO API...

Thanks.

Upvotes: 0

Views: 950

Answers (1)

Tapac
Tapac

Reputation: 2337

In Exposed DAO all references work with id column, so it's impossible to get it to work except if you'll define external_id as an id column like:

    object UserTable : IdTable<Int>("Users") {
        val pkColumn = integer("id").autoIncrement()
        val external_id = integer("external_id")
        override val id: Column<EntityID<Int>> = external_id.entityId()
    }

Upvotes: 0

Related Questions