3

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!

jbrookover
  • 5,100
  • 1
  • 23
  • 23

1 Answers1

2

You can use a EnumUserType, see this Question.

Community
  • 1
  • 1
moritz
  • 5,094
  • 1
  • 26
  • 33
  • 1
    It took me a bit to see how this would be used. The implementation is here: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-property A custom UserType can be applied to a field and is, essentially, that converter I was looking for. – jbrookover Mar 19 '11 at 17:06