java Hibernate enum throw Unknown name value [true] for enum class

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30280426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:49:10  来源:igfitidea点击:

Hibernate enum throw Unknown name value [true] for enum class

javaspringhibernateenumshibernate-mapping

提问by Talha Bin Shakir

I am using MySQL and I have a columns data type as Enum, I have define an enum type in my Entity However when query executes to retrive data it throws following exception:

我正在使用 MySQL 并且我有一个列为Enum的列数据类型,我在我的实体中定义了一个枚举类型但是当查询执行以检索数据时,它会引发以下异常:

Caused by: java.lang.IllegalArgumentException: Unknown name value [true] for enum class [com.myproject.MyEnum]
    at org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:467)
    at org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:452)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)

Following is my Entity and Enum source

以下是我的实体和枚举源

public enum MyEnum {
    TRUE("true"),
    FALSE("false");

    private final String name;

    private MyEnum (String name){
        this.name = name;
    } 

    public String toString(){
        return name;
    }
}

In my table structure I have define enum{true,false}

在我的表结构中,我定义了 enum{true,false}

@Entity
@Table(name="networthcashother")
public class Networthcashother {
    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String assetName;
    private String assetDescription;

    @Enumerated(EnumType.STRING)
    private MyEnum  married; 

    public MuEnum getMarried() {
        return married;
    }

    public void setMarried(MyEnum married) {
        this.married = married;
    }
}

However If I change my entity property type from Enum to boolean it works fine. Whats m doing wrong.

但是,如果我将实体属性类型从 Enum 更改为 boolean 它工作正常。我做错了什么。

回答by Vlad Mihalcea

The EnumType.STRINGwill use the EnumString representation, meaning it will call:

EnumType.STRING将使用Enum字符串表示,这意味着它会调用:

  • toString() - when converting the Enumto a Stringrepresentation
  • valueOf()- when converting the Stringrepresentation back to an Enum
  • toString() - 将 转换EnumString表示时
  • valueOf()- 将String表示形式转换回Enum

Because you can't override valueOf(), the default implementation will use the value returned by name()instead.

因为您不能覆盖valueOf(),所以默认实现将改用 返回的值name()

To fix it, you need to add the following static method to your Enum:

要修复它,您需要将以下静态方法添加到您的 Enum 中:

public static MyEnum getEnum(String value) {
    for(MyEnum v : values())
        if(v.getValue().equalsIgnoreCase(value)) return v;
    throw new IllegalArgumentException();
}