I have the following classificacao
field in a table.
This field is populated elsewhere and is filled with only 'P'
or 'N'
, acronyms for Positive and Negative .
I then created enum
Java.
Classification.java
public enum Classificacao {
POSITIVO('P'), NEGATIVO('N');
private char classificacao;
Classificacao(char classificacao) {
this.classificacao = classificacao;
}
public char getClassificacao() {
return classificacao;
}
}
In my entity, I have the attribute:
@Enumerated(EnumType.STRING)
@Convert(converter = ClassificacaoEnumConverter.class)
@Column(name = "classificacao", length = 1)
private Classificacao classificacao;
When I try to list this table, the following exception is thrown:
java.lang.IllegalArgumentException: Unknown name value [N] for enum class [br.com.jpalab.enums.Classificacao]
I understand why the error, it looks for the value N
, being that there is only POSTIVO
and NEGATIVO
, but how could I solve this problem?
I created this Converter
@Converter
public class ClassificacaoEnumConverter implements AttributeConverter<Classificacao, String> {
@Override
public String convertToDatabaseColumn(Classificacao classificacao) {
return String.valueOf(classificacao.getClassificacao());
}
@Override
public Classificacao convertToEntityAttribute(String classificacaoFromDb) {
if (classificacao == null) return null;
switch (classificacaoFromDb) {
case "P":
return Classificacao.POSITIVO;
case "N":
return Classificacao.NEGATIVO;
}
throw new IllegalStateException();
}
}