Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 581
Talha Bin Shakir Avatar asked Mar 16 '23 00:03

Talha Bin Shakir


1 Answers

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();
}
like image 93
Vlad Mihalcea Avatar answered Mar 23 '23 00:03

Vlad Mihalcea