开发者

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 n开发者_运维百科ull:

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.


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.


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;
}


I'm having exactly same problem after upgrading HSQLDB from 1.8 to 2.2.6. For enums Hibernate creates columns of type CHARACTER which is a fixed length column (contrary to VARCHAR). The length of it probably determined as a length of the longest enum value. INSERT/UPDATE statements are generated correctly by Hibernate, but when reading values from the table those shorter values come out appended with white spaces.

So, it seems that HSQLDB driver does not trim them. And if it should, I think the bug should be filed for HSQLDB, not Hibernate. However, if this behaviour of HSQLDB is compatible with SQL standard, then it's the Hibernate's EnumType should do trimming when reading enum values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜