Hibernate provides @Enumerated
annotation which supports two types of Enum
mapping either using ORDINAL
or STRING
. When we map using EnumType.STRING
, it takes the "name" of the Enum
and not the toString()
representation of the Enum. This is a problem in scenarios where the database column consists of only one character. For example, I have the following Enum:
public enum Status{ OPEN{ @Override public String toString(){ return "O";} }, WAITLIST{ @Override public String toString(){ return "W";} }, COMPLETE{ @Override public String toString(){ return "C";} } }
When I persist the enum Status.OPEN
using @Enumerated(EnumType.STRING)
, the value that Hibernate tries to store in the database is OPEN. However, my database column consists of only one character and hence it throws an exception.
One way to overcome this issue is to change the Enum type to hold single characters (like STATUS.O
, STATUS.W
instead of STATUS.OPEN
, STATUS.WAITLIST
). However, this reduces readability. Any suggestions to preserve the readability as well as mapping the Enum to a single character column?
Thanks.
By default, Hibernate maps an enum to a number. It uses the ordinal value, which is the zero-based position of a value within the definition of the enum. So, the enum value that's defined first gets mapped to 0, the second one to 1 and so on.
Define Hibernate Mapping FileThe <class> elements are used to define specific mappings from a Java classes to the database tables. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute.
hibernate mappings are one of the key features of hibernate . they establish the relationship between two database tables as attributes in your model. that allows you to easily navigate the associations in your model and criteria queries.
The best to customize mapping for enums is to use AttributeConverter
i.e:
@Entity public class Person { ... @Basic @Convert( converter=GenderConverter.class ) public Gender gender; } public enum Gender { MALE( 'M' ), FEMALE( 'F' ); private final char code; private Gender(char code) { this.code = code; } public char getCode() { return code; } public static Gender fromCode(char code) { if ( code == 'M' || code == 'm' ) { return MALE; } if ( code == 'F' || code == 'f' ) { return FEMALE; } throw ... } } @Converter public class GenderConverter implements AttributeConverter<Gender, Character> { public Character convertToDatabaseColumn(Gender value) { if ( value == null ) { return null; } return value.getCode(); } public Gender convertToEntityAttribute(Character value) { if ( value == null ) { return null; } return Gender.fromCode( value ); } }
You can find it in Hibernate docs: http://docs.jboss.org/hibernate/orm/5.0/mappingGuide/en-US/html_single/#d5e678
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