Suppose I have this enum:
public enum TestEnum { EXAMPLE, FURTHER_EXAMPLE, LAST_EXAMPLE }
With this mapping in the .hbm
:
<property name="testEnum" column="TEST_COLUMN"> <type name="org.hibernate.type.EnumType"> <param name="enumClass">p.a.c.k.TestEnum</param> </type> </property>
The enum is sent to the database as 0
, 1
, 2
. I'd like the values to be instead stored as EXAMPLE
, FURTHER_EXAMPLE
or LAST_EXAMPLE
in a varchar column.
How can I map enum to a varchar column?
Hibernate supports the mapping of Java enums as basic value types in various ways. The @Enumerated annotation is the original JPA-compliant way to map enums. This way, enums are stored according to one of two strategies. Using EnumType.ORDINAL: stores the enum according to the enum value’s ordinal position within the enum class.
In JPA, Enum types must be marked with the @Enumerated annotation, which can take an EnumType defining if the Java Enumeration is mapped to either a String or an Integer column type. To map the Enum to a String database column type, you need to specify the EnumType.STRING value when using the @Enumerated annotation.
Unfortunately, you can’t use Hibernate’s default mapping to map your Java enum to a PostgreSQL enum. As explained earlier, Hibernate maps the enum values to an int or a String. But PostgreSQL expects you to set the value as an Object. If you want to map your enum to PostgreSQL’s enum type, you need to implement a custom mapping.
From the below image EMPLOYEE ordinal is “0” and STUDENT ordinal is “1”. Ordinal value can be retrieved by using ordinal (). 3. Hibernate Enum mapping : In User.java, from above code snippet line number 23 describe the Hibernate enum mapping of UserType enum. If you want to save the position of Enum constant use EnumType.ORDINAL. 4.
Add this as a parameter of EnumType:
<param name="type">12</param>
This is because 12
is equivalent to java.sql.Types.VARCHAR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With