Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 763
sjahan Avatar asked Oct 12 '25 11:10

sjahan


1 Answers

If using Hibernate version > 6 this changed and should look like this:

@Type(StringArrayType.class)
@Column(
    name = "sensor_names",
    columnDefinition = "text[]"
)
private String[] sensorNames;

@Type(IntArrayType.class)
@Column(
    name = "sensor_values",
    columnDefinition = "integer[]"
)
private int[] sensorValues;

@Type(
    value = EnumArrayType.class,
    parameters = @Parameter(
        name = AbstractArrayType.SQL_ARRAY_TYPE,
        value = "sensor_state"
    )
)
@Column(
    name = "sensor_states",
    columnDefinition = "sensor_state[]"
)
private SensorState[] sensorStates;

Note: EnumArrayType comes from library HypersistenceUtils

like image 168
Strinder Avatar answered Oct 16 '25 07:10

Strinder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!