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
Hibernate enum throw Unknown name value [true] for enum class
提问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.STRING
will use the Enum
String representation, meaning it will call:
在EnumType.STRING
将使用Enum
字符串表示,这意味着它会调用:
- toString() - when converting the
Enum
to aString
representation - valueOf()- when converting the
String
representation back to anEnum
- toString() - 将 转换
Enum
为String
表示时 - 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();
}