Mapping enum types with Hibernate Annotations

44,409

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.

Share:
44,409
Thiago
Author by

Thiago

Just a lazy undergrad ;)

Updated on August 27, 2020

Comments

  • Thiago
    Thiago over 3 years

    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

  • Thiago
    Thiago about 14 years
    Thanks! I think that's exactly what I was looking for. I'm gonna try it out
  • Thiago
    Thiago about 14 years
    What can I type for the @Id field of the enum class?
  • Devanshu Mevada
    Devanshu Mevada about 14 years
    @Thiago What? Your enum is typically not an entity, it doesn't have an @Id field. Can you update your question to show what you're doing?
  • Thiago
    Thiago about 14 years
    Got it working. I was trying to use enum like an entity AND using its type-safety on Java side,but I understood that Hibernate associates a string to each enum (or integer, depends on EnumType), so that when you ask him to save, he fills with the string on the query automatically. Many thanks!
  • Blankman
    Blankman about 12 years
    could you assign a numerical value to each enum and persist that somehow?
  • Dinei
    Dinei almost 7 years
    For those with the same doubt as @Blankman, this is another question.