Better way to implement reverse mapping of custom enum ordinals?
Quite often databases will have columns that are stored as integers,
but represent enumerated values. In object-relational mapping, it's a
good idea to translate that integer value to the enumerated value it
represents.
The built-in "ordinal" value of an enum is almost useless. The integer
values for an enum always need to be controlled, and can't change if
you reorder things.
So you at least have to implement one custom field in the enum, which
I'll call "columnValue".
Somewhere you have to have code that translates those integer values
into the enumerated type value. The best place to do that is within
the enumerated type itself. Ideally, I'd like to do this in a way
that doesn't repeat the integer values, and is reasonably efficient.
A simple-minded implementation might look like this:
public static enum SomeType {
Foo(101),
Bar(100),
Gork(4001);
private int columnValue;
public final int getColumnValue() { return columnValue; }
public final void setColumnValue(int columnValue)
{ this.columnValue = columnValue; }
public SomeType getEnum(int columnValue) {
switch (columnValue) {
case 101: return Foo;
case 100: return Bar;
case 4001: return Gork;
default: return null;
}
}
SomeType(int columnValue) {
this.columnValue = columnValue;
}
}
Can someone think of a better way to do this, that doesn't repeat the
column values?