Reputation: 31212
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?
Upvotes: 0
Views: 469
Reputation: 11531
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?
Upvotes: 1