Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA mapping a map where key is an Enum

I'm trying to create an entity where one of the field is a Map with Enum key:

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;
}

The Attribute is just a simple enumeration with no additional fields or logic:

public enum Attribute {
    ATTRIBUTE1, ATTRIBUTE2, ATTRIBUTE3;
}

This maps nicely and do work. But the collection table, attributes creates with integer column definition for my map key, as the default is EnumType.ORDINAL. For my purposes I need it to be string, but I can't just place @Enumerated(EnumType.STRING) on my field as this leads to an exception.

Do I have any options of how can I achieve this desired behaviour? Thanks very much.

like image 914
DruidKuma Avatar asked Aug 07 '16 09:08

DruidKuma


1 Answers

Kudos to @BilalBOUTAYA

The answer is: use @MapKeyEnumerated.

The @Enumerated annotation applies to the value column which is obviously incompatible with the annotation.

Example:

@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<>();
like image 196
usr-local-ΕΨΗΕΛΩΝ Avatar answered Oct 08 '22 02:10

usr-local-ΕΨΗΕΛΩΝ