Java – How to convert a Hibernate String column to an Enum

enumshibernatejavatypes

I currently have a simple String field in a Hibernate persisted class:

 private String font = "Times New Roman";

"Times New Roman" is the default value, so many stored objects have that data. For several reasons, I would like to convert this to an Enum:

 @Enumerated(EnumType.String)
 private FontEnum font = FontEnum.TIMES;

Hibernate uses Enum.valueOf(clazz, string) to convert the column data, which would fail on "Times New Roman" due to the spaces.

Googling suggests overriding Enum.valueOf() is impossible; do others know differently? Can I fool Enum.valueOf() to convert "Times New Roman" to FontEnum.TIMES?

Or, can I create a custom Hibernate converter like:

 public FontEnum legacyConverter(String old);

and add

 @Enumerated(EnumType.String)
 @Converter(Converters.legacyConverter()) // Does this exist?
 private FontEnum font = FontEnum.TIMES;

to my fields? I haven't seen anything like that.

I know a fallback method would be to add some pre-persist logic that slowly migrates the data to another column, but I'd like to avoid that.

Thank you – it's my first question on StackOverflow!

Best Answer

You can use a EnumUserType, see this Question.