javapostgresqlhibernatekotlinhibernate-mapping

Hibernate mapping between Postgres array of varchar and a Java/Kotlin collection of enum


Basically everything is in the title.

I have a column in my DB which is a varchar[].

I really would like to map it to a Java/Kotlin enum. We've already got this working to fetch it as a list of Strings (through com.vladmihalcea:hibernate-types and StringArrayType), but not with a mapping to an enum. Do you know if this is possible?

Since we know how to map a varchar to an enum, and a varchar[] to a collection of String, I would be tempted to think that this should possible, but I didn't succeed yet.

Here would be a simple sample of my current configuration:

CREATE TABLE test(my_values varchar[]) ;
INSERT INTO test(my_values) values ('{VAL1, VAL2}')
@Entity
@Table(name = "test")
data class DbTest(
        @Column(name = "my_values")
        val myValues: List<Values>
)

enum class Values {
       VAL1, VAL2
}

I tried this: https://vladmihalcea.com/map-postgresql-enum-array-jpa-entity-property-hibernate/ which looks pretty good but you have to define the enum in the DB and we don't want that.

Thanks!


Solution

  • I'm posting my solution, I didn't succeed to get a List<Values>, although I got an Array<Values> which was fine with me.

    @Entity
    @Table(name = "test")
    @TypeDef(
            name = "values-array",
            typeClass = EnumArrayType::class,
            defaultForType = Array<Values>::class,
            parameters = [
              Parameter(
                      name = EnumArrayType.SQL_ARRAY_TYPE,
                      value = "varchar"
              )
            ]
    )
    data class DbTest(
            @Type(type = "values-array")
            @Column(name = "my_values", columnDefinition = "varchar[]")
            val myValues: Array<Values>
    )
    
    enum class Values {
           VAL1, VAL2
    }
    

    This is working like a charm and I can map my array to a list and vice versa quite easily, which is ok.

    Hoping this will help someone someday ;)