Hibernate provides @Enumerated
annotation which supports two types of Enum
mapping either using ORDINAL
or STRING
. When we map using EnumType.STRING
, it takes the "name" of the Enum
and not the toString()
representation of the Enum. This is a problem in scenarios where the database column consists of only one character. For example, I have the following Enum:
public enum Status{
OPEN{
@Override
public String toString(){
return "O";}
},
WAITLIST{
@Override
public String toString(){
return "W";}
},
COMPLETE{
@Override
public String toString(){
return "C";}
}
}
When I persist the enum Status.OPEN
using @Enumerated(EnumType.STRING)
, the value that Hibernate tries to store in the database is OPEN. However, my database column consists of only one character and hence it throws an exception.
One way to overcome this issue is to change the Enum type to hold single characters (like STATUS.O
, STATUS.W
instead of STATUS.OPEN
, STATUS.WAITLIST
). However, this reduces readability. Any suggestions to preserve the readability as well as mapping the Enum to a single character column?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…