Search code examples
javahibernatejpaenumshibernate-mapping

How to I map an enum ordinal to it's value in hibernate?


I have 2 database tables:

  1. Persists a class, that has a field who's type is an enum. In the respective column, the enum value's ordinal is stored.
  2. Persists the enum values' ordinal and name.

How do I use a Hibernate Mapping to map the enum's ordinal in table 1 to the name stored in table 2?

Edit: Basically, with a SQL SELECT, I would join the 2 tables using the ordinal, to get the name. I'm not sure how I would do that in hibernate though.

This isn't a duplicate; I'm not using Hibernate reverse engineering.


Solution

  • I solved this by creating a custom implementation of org.hibernate.usertype.EnhancedUserType, overriding nullSafeGet, nullSafeSet, fromXMLString, objectToSQLString and toXMLString to all use the ordinal instead of the name.

    It works, but I don't like it because it defeats the purpose of an enum, to not have to deal with messing with the ordinal value. As it stands, reordering the enum values will invalidate all data in the database.

    This solution completely ignores the 2nd table, the one that stores the enum's ordinal and name.