Is there a way to use a custom strategy to map enum types in JDBI3?

1.5k views Asked by At

I have a simple scenario where an enum is being sent for storage and I want to pull it out. However, I cannot use either Ordinal nor Name strategy. The value being stored is a value inside each enum instance.

TLDR: Is there a way for me to register a mapper that does one thing on persistance and another on retrieval?

DISCLAIMER: I am not using posgres

// A simple enum
enum class N(val v: Int) {
    A(10),B(15);
    companion object {
        val map = values(v: Int).associateBy { it.v }
        fun from(v: Int) = map.getValue(v)
    }
}

// A simple data class
data class A(val i: Int = 0, val n: N = N.A) {
    interface Dao {
        @SqlUpdate("INSERT INTO a (i) VALUE (?)")
        @GetGeneratedKey
        fun insert(i: Int): Int
        @SqlQuery("SELECT i,n FROM a WHERE i = ?")
        fun select(i: Int): A
    }
}

// register my enum so that it stores the int value
jdbi.registerArgument(object : AbstractArgumentFactory<N>(Types.TINYINT) {
    override fun build(value: N, config: ConfigRegistry): Argument {
        return Argument { pos, stmt, _ -> stmt.setInt(pos, value.value) }
    }
})

// test with Ordinal strategy
jdbi.configure(Enums::class.java) { it.setEnumStrategy(EnumStrategy.BY_ORDINAL) }

The simplest table possible

create table a(i int primary key auto_increment, n int);

I am trying to pull the data out but I get the following error: Exception in thread "main" org.jdbi.v3.core.result.UnableToProduceResultException: no N value could be matched to the name 15

val dao = jdbi.onDemand(A.Dao::class.java)
val i = dao.insert(N.B)
printf(dao.select())

I know that I am using AbstractArgumentFactory which I think is the root of my problem. I don't think this helper is flexible to my needs.

Is there a way for me to register a mapper that does one thing on persistance and another on retrieval?

1

There are 1 answers

0
hanzo2001 On

I think I found the solution. Much simpler than I expected

jdbi.registerColumnMapper(object : ColumnMapper<N> {
    override fun map(r: ResultSet, columnNumber: Int, ctx: StatementContext): N {
        val v = r.getInt(columnNumber)
        return N.from(v)
    }
})

After I dove into the Jdbi project and took a look at

org.jdbi.v3.core.mapper.EnumMapper

I made it work in a scratch file