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:
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}
@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.
1 Answer 1
The EnumType.STRING will use the Enum String representation, meaning it will call:
- toString() - when converting the Enumto aStringrepresentation
- valueOf() - when converting the Stringrepresentation back to anEnum
Because you can't override valueOf(), the default implementation will use the value returned by name() instead.
To fix it, you need to add the following static method to your Enum:
public static MyEnum getEnum(String value) {
 for(MyEnum v : values())
 if(v.getValue().equalsIgnoreCase(value)) return v;
 throw new IllegalArgumentException();
}
3 Comments
Explore related questions
See similar questions with these tags.