Hibernate Tips is a series of posts in which I describe a quick and easy solution for common Hibernate questions. If you have a question you like me to answer, please leave a comment below.
How can I map an enum attribute to a database column? Which option should I prefer?
JPA and Hibernate provide 2 standard options to map an Enum to a database column. You can either use its String representation or its ordinal value.
Both approaches have their drawbacks:
The String representation is verbose, and the renaming of an enum value requires you to also update your database.
The ordinal of an enum value is its position in the enum declaration. This value changes which requires you to update your database when you remove an existing value or don’t add new values to the end of the Enum declaration.
You can define a custom mapping and avoid these issues with an AttributeConverter.
When you use JPA’s and Hibernate’s standard mapping, you can either rely on the default mapping using the ordinal or specify the mapping approach. You can do that with an @Enumerated annotation as I show you in the following examples.
If you don’t provide an @Enumerated annotation or don’t set an EnumType as its value, the ordinal of the enum value gets mapped to the database.
If you want to map the String representation to the database, you need to annotate the entity attribute with @Enumerated and set EnumType.STRING as its value.
You can learn more about AttributeConverter and how you can use them to define custom mappings for enums and other Java types in:
- How to implement a JPA AttributeConverter
- JPA 2.1 Attribute Converter – The better way to persist enums
- How to persist LocalDate and LocalDateTime with JPA
Hibernate Tips Book
Get more recipes like this one in my new book Hibernate Tips: More than 70 solutions to common Hibernate problems.
It gives you more than 70 ready-to-use recipes for topics like basic and advanced mappings, logging, Java 8 support, caching, and statically and dynamically defined queries.
Get it now!