简体   繁体   中英

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?

您需要为Enum定义自定义UserType

Generally, you should not do that. If the two (or more enums) can be assigned to the same field, then merge them into one anum.

If you are using inheritance, like: Vehicle with two subclasses - Boat and Car , then you can have a different field in each subclass - after all each of these enums is relevant only to the particular type. So:

@Column
private BoatType boatType;

I don't think this can work easily with multiple Enum types trying to co-exist in the same property. How does hibernate know which Enum class it should be instantiating when it loads the field out of the DB?

If you really want to do this you'd need to somehow encode the enum class + the value every time you persist this property (use a custom UserType as duffymo suggests).

Can you not break this into two proprties, one per enum class? Then you can declare enumValue (and enumValue2) as the correct class and it will work out of the box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM