简体   繁体   English

在 Postgres 的 varchar 数组和枚举的 Java/Kotlin 集合之间的 Hibernate 映射

[英]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[] .我的数据库中有一个列是varchar[]

I really would like to map it to a Java/Kotlin enum .我真的很想将它映射到 Java/Kotlin enum We've already got this working to fetch it as a list of String s (through com.vladmihalcea:hibernate-types and StringArrayType ), but not with a mapping to an enum.我们已经将它作为String列表(通过com.vladmihalcea:hibernate-typesStringArrayType )获取,但没有映射到枚举。 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.由于我们知道如何将varchar映射到enum ,以及如何将varchar[]映射到String的集合,我很想认为这应该是可能的,但我还没有成功。

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.我试过这个: https://vladmihalcea.com/map-postgresql-enum-array-jpa-entity-property-hibernate/看起来很不错,但你必须在数据库中定义枚举,我们不希望那样。

Thanks!谢谢!

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.我正在发布我的解决方案,但我没有成功获得List<Values> ,尽管我得到了一个Array<Values> ,这对我来说很好。

@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 ;)希望有一天这会帮助某人;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM