Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate map enum to varchar

Tags:

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?

like image 307
ipavlic Avatar asked Mar 23 '12 12:03

ipavlic


People also ask

How do I map enums in hibernate?

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.

How to map an enum to a string in JPA?

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.

Can hibernate map enums from Java to PostgreSQL?

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.

How to retrieve ordinal value from Hibernate enum in Java?

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.


1 Answers

Add this as a parameter of EnumType:

<param name="type">12</param> 

This is because 12 is equivalent to java.sql.Types.VARCHAR

like image 100
bvulaj Avatar answered Oct 03 '22 11:10

bvulaj