With standard JDO and JPA you can persist a Java enum field as either the name (String-based column) or the ordinal (Number-based column). This is great as far as it goes, so we can easily persist fields using this enum.
public enum Colour{RED, GREEN, BLUE;}
In some situations however you want to configure what is stored. Say, we want to store a numeric value for each enum constant but not the default values (for some reason). In DataNucleus up to and including v4 (for RDBMS only!) we allowed persistence of
public enum Colour { RED(1), GREEN(3), BLUE(5); int code; private Colour(short val) {this.code = val;} public short getCode() {return this.code;} public static Colour getEnumByCode(short val) { case 1: return RED; case 3: return GREEN; case 5: return BLUE; } }
and then you set metadata for each enum field of this type to specify that you want to persist the “code” value, like this
@Extensions({ @Extension(vendorName="datanucleus", key="enum-getter-by-value", value="getEnumByCode"), @Extension(vendorName="datanucleus", key="enum-value-getter", value="getCode") }) Colour colour;
This was fine, except required too much of the user.
DataNucleus v5 simplifies it, and you can now do
public enum Colour { RED(1), GREEN(3), BLUE(5); int code; private Colour(short val) {this.code = val;} public short getCode() {return this.code;} }
and mark each enum field like this
@Extension(vendorName="datanucleus", key="enum-value-getter", value="getCode") Colour colour;
We don’t stop there however, because the value that is persisted using this extended method can now be either short, int or String. It is also now available for use on RDBMS, Cassandra, MongoDB, HBase, Neo4j, ODF, Excel, and JSON, so your code is more portable too!