Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist raw Java Enum using Hibernate

I have an entity that contains an enum property. That property can be any one of my types of Enums in my codebase:

public enum AutomobileType {
   CAR, TRUCK, MOTORCYCLE
}

public enum BoatType {
   ROW_BOAT,YACHT,SHIP
}

@Entity
public class FooBar {

  @Enumerated(value=EnumType.ORDINAL)
  private Enum enumValue;

  public void setEnumValue(Enum value) { ... }
  public Enum getEnumValue() { ... }
}

This fails with an exception, "Wrong data type: For input string: "[B@f0569a". I changed FooBar to store the property as an Integer which works, but that's not what I need. I need the actual enum. Any suggestions on how to make this work so that the Enum can be persisted as int but later pulled out into the correct Enum type?

like image 367
codecraig Avatar asked Jan 14 '11 13:01

codecraig


People also ask

Can enum values be persisted?

Enum values are persisted in the database, regardless of the enum that is extended. Therefore, when an enum is made extensible, the enum values that are used on any system will prevail.

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 save an enum in Java?

First of all, in order to save enum values in a relational database using JPA, you don't have to do anything. By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers.


1 Answers

You need to define a custom UserType for the Enum.

like image 128
duffymo Avatar answered Oct 18 '22 15:10

duffymo