Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping enum types with Hibernate Annotations

I have an enum type on my Java model which I'd like to map to a table on the database. I'm working with Hibernate Annotations and I don't know how to do that. Since the answers I search were rather old, I wonder which way is the best?

Thanks in advance

like image 543
Thiago Avatar asked Apr 02 '10 20:04

Thiago


People also ask

How annotate enum in hibernate?

You can specify how the enum should be persisted in the database with the EnumType enum property of the @Enumerated annotation. EnumType. ORDINAL specifies that the enum will be persisted as an integer value. Here, myEnum set to VALUE1 would be persisted as 0, VALUE2 as 1, etc.

How does hibernate store enums?

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.

How do I map an enum to a column in a database?

To map the Enum to a String database column type, you need to specify the EnumType. STRING value when using the @Enumerated annotation. As expected, the String representation of the Java Enum was used to populate the associated database column value.

Which annotation in JPA may be used to specify whether enum should be persisted as number in database?

The @Enumerated annotation enables you to define how an enum attribute gets persisted in the database. By default, all JPA implementations map the ordinal value of the enum to a numeric database column.


1 Answers

Do you need something else than the @Enumerated annotation? For example, the following enum:

public enum MyEnum {      VALUE1, VALUE2;  }   

Could be used and annotated like this:

private MyEnum myEnum; @Column(name="myenum")  @Enumerated(EnumType.ORDINAL)  public MyEnum getMyEnum() {      return myEnum  } 

You can specify how the enum should be persisted in the database with the EnumType enum property of the @Enumerated annotation. EnumType.ORDINAL specifies that the enum will be persisted as an integer value. Here, myEnum set to VALUE1 would be persisted as 0, VALUE2 as 1, etc.

The alternative is to use EnumType.STRING to specify that the enum will be persisted using the name of the enum value that the field is set to. So, applied to the previous example, setting the field myEnum to MyEnum.VALUE1 will persist as VALUE1, etc.

like image 153
Pascal Thivent Avatar answered Oct 13 '22 00:10

Pascal Thivent