2011-05-16 82 views
0

有两个EnumType:如EnumType.ORDINALEnumType.STRING。但是都有disvantages:如何翻译@Enumerated属性的名称?

EnumType.ORDINAL: You must preserve the enum order. 

EnumType.STRING: The column width is the max length of the enum names, which maybe very long. 

相反,我想介绍一个缩写为枚举类型:

public Enum MonthEnum { 
    January("JAN"), 
    February("FEB"), 
    March("MAR"), 
    ...; 

    String abbrev; 

    static Map<String, MonthEnum> abbrevs = new HashMap(); 

    MonthEnum(String abbrev) { 
     this.abbrev = abbrev; 
     abbrevs.put(abbrev, this); 
    } 

    public static MonthEnum fromAbbrev(String abbrev) { 
     return abbrevs.get(abbrev); 
    } 
} 

@Entity 
class Diary { 
    @Enumerated(ABBREV) 
    Month month; 
} 
+0

[使用Hibernate注释来保留枚举属性的自定义值](http://stackoverflow.com/questions/5032116/using-hibernate-annotations-to-persist-custom-value-for-enumerated-attribute ) – axtavt 2011-05-16 09:00:37

回答

1

它不能在JPA 2.0来完成。但是它可以在使用UserType的Hibernate中完成。但你为什么想要。我已经考虑过你的字符串变体的参数,但是这个参数不适用于数据库中的任何字符串(varchar)列。还请考虑一下,枚举可能会用在JAVA代码中,所以长枚举字符串值也会成为问题。