Implement a custom enum mapping with an AttributeConverter

preview_player
Показать описание
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.
But what do you do, if you need to map values from a legacy database that don’t match these standard mappings?
Or if you don’t want to accept the drawbacks of the standard mapping?
The String representation is verbose, and renaming an enum value requires you also to update your database.
The ordinal of an enum value is its position in the enum declaration. This value changes and 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.

In all these situations, you need to define a custom mapping. But no worries, that’s pretty easy since JPA 2.1 introduced AttributeConverter.

If you like this video, please give it a thumbs up and share it with your friends and co-workers.

Like my channel? Subscribe!

Join the free Member Library:

Want to connect with me?
#JPA #HIbernate #AttributeConverter #Tutorial
Рекомендации по теме
Комментарии
Автор

The best solution i came across to this date.. I also wonder why still there is no simple annotation to do it all behind the scene.

m_sharif
Автор

Very good video! Saved the problem I had for monthes! Thanks.

renatobaratagomes
Автор

Hello Thorben,
1. Wouldn't this approach adds an overhead to document the shortName explaination? If I am a DBA- "N", "S", "P" are not known to me, so developer need to document it e.g "N" stands for NOT_PUBLISHED, right?

puspendertanwar
visit shbcf.ru