user1479203 user1479203 - 2 months ago 25
Java Question

How to map custom enumurated integer ordinals with hibernate

I have an enum class named Status as follows

public enum Status {
PENDING(0), SUCCESS(1), FAILED(-1);

private int st;

private Status(int st){
this.st = st;
}
}


and from other class I try to map this status enum

public void setStatus(Status status) {
this.status = status;
}

@Enumerated(EnumType.ORDINAL)
public Status getStatus() {
return status;
}


when I run this code, I get


java.lang.IllegalArgumentException: Unknown ordinal value for enum class data.Status: -1
at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:93)
at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:124)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
at


but I already have -1 in enum definition.

Answer

You could define your own UserType which defines how Hibernate should map those enums.

Note that the ordinal defines the index of the enum value and thus FAILED would have the ordinal 2. To map the enum using its properties your need a UserType implementation.

Some links: