I'm trying to retrieve an enum from a database and Hibernate doesn't find the property value and therefore throws the following Exception java.lang.IllegalArgumentException: No enum constant com.intrawa.qx.validator.models.entity.Group.CONFIGTAB.false
The problem occurs when hibernate calls the valueof method of the enum: at java.lang.Enum.valueOf(Enum.java:238)
I'm working with a Database where I cannot change it's column names.
For example look at the code:
@Entity
@Data
@Table(name = "bm_host_groups")
public class Group {
@Enumerated(EnumType.STRING)
private CONFIGTAB configTab;
@AllArgsConstructor
private enum CONFIGTAB {
TRUE("true"),
FALSE("false");
@Getter @Setter
private String value;
}
}
The DB has a column called configTab with enum value type and two possible values ("true", "false"), when hibernate call valueof("true") it doesn't find TRUE and throws the exception.
One solution I found it's on this post: What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?
However, it needs a custom method that takes for example "true" as argument from the DB then capitallize it in order to find the value of the enum.
I searched a way to override Enum's valueof() but this post says it's not possible and basically suggest the same as the first solution, make a custom method and make the client calls it. Post: Override valueof() and toString() in Java enum
Is there a way to make hibernate call a custom method instead of valueof()?
It is not possible to override valueOf()
. But it is possible to manipulate the value that valueOf()
will get. Namely, the correct solution is to use AttributConverter
and discard the @Enumerated
annotation, like:
@Getter @Setter
//@Enumerated(EnumType.STRING)
@Convert(converter=ConfigTabConverter.class)
private CONFIGTAB configTab;
Converter is quite simple:
@Converter(autoApply=true)
public class ConfigTabConverter
implements AttributeConverter<CONFIGTAB,, String> {
@Override
public String convertToDatabaseColumn(CONFIGTAB attribute) {
return attribute.getValue();
}
@Override
public CONFIGTAB convertToEntityAttribute(String dbData) {
return CONFIGTAB.valueOf(dbData.toUpperCase());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With