0

My enum looks something like this

public enum EventType {

    DATASET_DELETION("DSDEL");

    private static final Map<String, EventType> dbIdLookup = new HashMap<>();

    static {
        for (EventType type : EnumSet.allOf(EventType.class)) {
            String databaseID = type.getId();
            dbIdLookup.put(databaseID, type);
        }
    }

    private String id;

    EventType(String _id) {

        this.id = _id;
    }

    public String getId() {
        return this.id;
    }

    public EventType getFromDatabaseID(String _databaseID) {

        EventType result = dbIdLookup.get(_databaseID);

        return result;
    }
}

where DATASET_DELETION is what I would like to refer to the field value in the java code and DSDEL is the value I want to map it to in the database. I want the database code to be more compact and the java label more readable.

My current mapping doesn't work:

@Column(name = "EVENT_TYPE")
private EventType type;

Throwing

java.lang.RuntimeException: java.lang.IllegalArgumentException: Unknown name value for enum class blah.blah.EventType: DSDEL

How can I map an enum to a database value that is not the primary label of the enum but one of its fields in the declaration?

1 Answer 1

1

JPA does not support arbitrary enum values, only providing support for "ordinal" or "name" persistence. Improvements have been requested for inclusion in JPA 2.2+ but who knows when (if) that will happen.

One way (that is portable) would be to provide a JPA AttributeConverter for that Enum type, so it converts the Enum to a String, and persists the arbitrary String value you have internally.

Some JPA providers support custom handling, like this one in DataNucleus JPA. Maybe your provider has something also?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.