Hibernate provides @Enumerated
annotation which supports two types of Enum
mapping either using ORDINAL
or STRING
. When w
Here is an example which uses annotations.
http://www.gabiaxel.com/2011/01/better-enum-mapping-with-hibernate.html
It's still based off of a custom UserType. Four and a half years later and I'm still not aware of a better way to do this.
Typically, I persist my enum values as a char / int, some simple ID, then use a transient method that finds the appropriate enum by the simple ID value, e.g.
@Transient
public MyEnum getMyEnum() {
return MyEnum.findById(simpleId); //
}
and...
public enum MyEnum {
FOO('F'),
BAR('B');
private char id;
private static Map myEnumById = new HashMap();
static {
for (MyEnum myEnum : values()) {
myEnumById.put(myEnum.getId(), myEnum);
}
}
private MyEnum(char id) {
this.id = id;
}
public static MyEnum findById(char id) {
return myEnumById.get(id);
}
public char getId() {
return id;
}
}