Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate/JPA bug - Not recognizing some strings in a enum

I have an enum in a class, mapped by Hibernate. One of the mapped fields is and enum type which has one of the following values OK, NOK or NAP. NOK or NAP works as expected, but when the field the class is set to 'OK', Hibernate fails to map and retrieve the value, which is set to null:

java.lang.IllegalArgumentException: Unknown name value for enum class     com.a.b.c.d.Class$Status: OK
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:113)

The class has:

private Status status;

@JoinColumn(name = "STATUS")
@Enumerated(EnumType.STRING)
public Status getStatus() {
    return status;
}

public enum Status {
    OK, NOK, NAP;
}

If I change OK to OK2, it works correctly. _OK also works. As far as i'm concerned 'OK' is not a reserved name (like in this case where the guy uses new) as it compiles correctly.

Thanks!

UPDATE:

Up 'till now, what I did to solve the problem is to modify the enum and store '_OK' in the database instead of 'OK', as shown above. Not very nice solution, but it works at least.

public enum Status {
    _OK("OK"), 
    NOK("NOK"), 
    NAP("NAP");

    private String desc;

    private Status(String desc){
        this.desc = desc;
    }

    public String getDesc(){
        return desc;
    }
}

BUG REPORT:

A bug report has been filled.

like image 404
lucasarruda Avatar asked Jun 21 '11 22:06

lucasarruda


2 Answers

The problem you have is that in your database you have values others than OK, NOK, NAP and when you are retrieving the records is when you are getting the exception, not when you are persisting.

From your Exception com.a.b.c.d.Class$Status: OK2 it seems as your database has that value and hence the java.lang.IllegalArgumentException: Unknown name value for enum class exception.

Check your table for invalid values, remove/correct them, and try again.

like image 106
Marcelo Avatar answered Nov 14 '22 23:11

Marcelo


As a another workaround you can try providing an exact column definition to have a VARCHAR column:

@Column(columnDefinition = "VARCHAR(3)")
// @Column(columnDefinition = "VARCHAR2(3)") // VARCHAR2 for Oracle
@Enumerated(EnumType.STRING)
public Status getStatus() {
    return status;
}

public enum Status {
    OK, NOK, NAP;
}
like image 35
Vlad Avatar answered Nov 14 '22 22:11

Vlad