@DbEnumValue
The standard JPA mapping for Enum is somewhat dangerous. That is, the use of
EnumType.ORDINAL
values relies on the exact order of the Enum values
not changing (which is subtle, we can only add values to the end of the Enum).
The use of EnumType.STRING
is ok but either compromises the name of
the Enum values or the values being stored in the database.
@DbEnumValue
is provided to address these issues and can be used when
we can modify the Enum being used to add DB values for each enum value.
To use @DbEnumValue
we need to annotate a method that returns a
value that is used to map the Enum value into the database.
public enum Status {
NEW("N"),
ACTIVE("A"),
INACTIVE("I");
String dbValue;
Status(String dbValue) {
this.dbValue = dbValue;
}
// annotate a method that returns the value
// in the DB that the enum element maps to
@DbEnumValue
public String getValue() {
return dbValue;
}
}
Storage
We use the storage
attribute to specify the DB type that the
values map to. In effect we typically use this when we want to map the Enum
values to database INTEGER type.
public enum Status {
NEW("1"),
ACTIVE("2"),
INACTIVE("3");
String value;
Status(String value) {
this.value = value;
}
// map to DB INTEGER
@DbEnumValue(storage = DbEnumType.INTEGER)
public String getValue() {
return value;
}
}