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?
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.
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.
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.
You need to define a custom UserType for the Enum.
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