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!

1 Answer 1

2

You can use a EnumUserType, see this Question.

Sign up to request clarification or add additional context in comments.

1 Comment

It took me a bit to see how this would be used. The implementation is here: docs.jboss.org/hibernate/stable/annotations/reference/en/… A custom UserType can be applied to a field and is, essentially, that converter I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.