简体   繁体   English

使用Hibernate持久化原始Java Enum

[英]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? 这失败了,有一个例外,“错误的数据类型:对于输入字符串:”[B @ f0569a“。我改变了FooBar将属性存储为有效的整数,但这不是我需要的。我需要实际的枚举。任何建议关于如何使这个工作,以便枚举可以作为int持久化,但后来拉出正确的枚举类型?

您需要为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. 如果可以将两个(或多个枚举)分配给同一个字段,则将它们合并为一个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. 如果你正在使用继承,例如:具有两个子类的Vehicle - BoatCar ,那么你可以在每个子类中有一个不同的字段 - 毕竟每个枚举只与特定类型相关。 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. 我不认为这可以很容易地使用多个Enum类型试图在同一属性中共存。 How does hibernate know which Enum class it should be instantiating when it loads the field out of the DB? 当hibernate从DB加载字段时,它如何知道它应该实例化哪个Enum类?

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). 如果你真的想要这样做,你需要以某种方式编码枚举类+每次持久化这个属性的值(使用自定义UserType作为duffymo建议)。

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. 然后你可以将enumValue(和enumValue2)声明为正确的类,它将开箱即用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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