JPA映射密钥为Enum的映射

时间:2016-08-07 09:28:48

标签: java hibernate jpa dictionary enums

我正在尝试创建一个实体,其中一个字段是带有枚举键的Map:

public class MyEntity {

    @ElementCollection
    @CollectionTable(name="attributes", joinColumns=@JoinColumn(name="my_entity_id"))
    @MapKeyColumn(name = "attribute_key")
    @Column(name="attribute_value")
    private Map<Attribute, String> attributes;
}

Attribute只是一个简单的枚举,没有其他字段或逻辑:

public enum Attribute {
    ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3;
}

这很好地映射并且可以工作。但是收集表attributes为我的地图密钥创建了integer列定义,默认为EnumType.ORDINAL。出于我的目的,我需要将它作为字符串,但我不能将@Enumerated(EnumType.STRING)放在我的字段上,因为这会导致异常。

我有什么选择可以实现这种理想的行为吗? 非常感谢。

1 个答案:

答案 0 :(得分:8)

感谢@BilalBOUTAYA

答案是:使用@MapKeyEnumerated

@Enumerated注释适用于显然与注释不兼容的值列。

示例:

@JsonIgnore
@ElementCollection(fetch = FetchType.LAZY)
@CollectionTable(name = "FTT_REGISTRI_ESCLUSIONI", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "FTT_FK_ESCLUSIONE_TO_REGISTRO"), joinColumns = @JoinColumn(name = "REGISTRO_ID"))
@MapKeyColumn(name = "CLAUSOLA_ESCLUSIONE", length = 40, nullable = false)
@MapKeyClass(FttEsclusioneType.class)
@MapKeyEnumerated(EnumType.STRING)
@Column(name = "RECORD_COUNT", nullable = false)
protected final Map<FttEsclusioneType, Long> esclusioneRecordCounters = new HashMap<>();
相关问题