Persisting enums with JPA 2.0 is possible, but there is no nice way to do it. Using the @Enumerated annotation, you can use EnumType.ORDINAL or EnumType.STRING to map the enum value to its database representation. But both options have their drawbacks. The ordinal of an Enum depends on the ordering of its values and can create problems, if we need to add new ones. The String representation of an Enum is often quite verbose and renaming a value will break the database mapping. These drawbacks can be avoided by using an Attribute Converter.
Implementing the Converter
Now we can implement the converter to use the shortName property to store the Enum in the database:
But there is one thing we need to take care of and if you have read my former article about JPA Attribute Converter you might have wondered already. Attribute Converter cannot be applied to attributes annotated with @Enumerated. So we have to make sure that there is no @Enumerated annotation at our entity attributes of type Vehicle.
Using the Converter
We implemented a simple Attribute Converter that uses our own rules to convert the Vehicle enum to its database representation. So we can make sure that changing the values of the Vehicle enum will not break the existing/remaining mappings.
What do you think about using JPA Attribute Converter to persist enums? Please leave me a comment!
And if you like to read more about the features introduced with JPA 2.1, have a look at my JPA 2.1 overview: JPA 2.1 – 12 features every developer should know.