4

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.

Ali Faizan
5026 silver badges14 bronze badges
asked May 16, 2015 at 20:29

1 Answer 1

7

The EnumType.STRING will use the Enum String representation, meaning it will call:

  • toString() - when converting the Enum to a String representation
  • valueOf() - when converting the String representation back to an Enum

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();
}
answered May 16, 2015 at 21:53
Sign up to request clarification or add additional context in comments.

3 Comments

when will this method get called ? would it be an implicit call made while converting String to Enum or do i have to make this call?
@VladMihalcea when will this method get called ? or I need to manually call that mathod
This method will be called automatically by Hibernate. Basically, you just override the default implementation of this method.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.