I do not recommend using the ordinal of enum
as an identifier of it in the database. If you do this, adding a new element in the non-ending enumeration or rearranging them will generate an inconsistency in your database since the ordinal will change. Example:
Suppose you have the following enumeration:
public enum User Role {
REGISTERED_USER, ADMIN;
}
In this case, in your database you would have users with the REGISTERED_USER
privilege with the value 0 and ADMIN
with the value 1. Now suppose you add a new UserRole
:
public enum UserRole {
REGISTERED_USER, GUEST, ADMIN;
}
From now, REGISTERED_USER
has the value 0, GUEST
has the value 1 and ADMIN
the value 2. That is, all ADMIN
have become GUEST
!
Solution:
What you can do is assign a id
to each element and implement a AttributeConverter
. That way, with every new element you add, you just have to assign a new identifier that does not have to be sequential.
EntryType.java
public enum EntryType {
INCOME(0),
OUTPUT(1);
//para uso interno
//evita que arrays sejam criados desnecessariamente
private static final EntryType VALUES[] = EntryType.values();
private final int identificador;
private EntryType(int identificador) {
this.identificador = identificador;
}
public final int getIdentificador() {
return identificador;
}
//Caso queira, pode retornar um optional ao invés de lançar um exceção
public static final EntryType deIdentificador(int identificador) {
for(EntryType et : VALUES) {
if(et.identificador == identificador) {
return et;
}
}
throw new IllegalArgumentException("identificador inválido: " + identificador);
}
}
EntryTypeConverter
public final class EntryTypeConverter implements AttributeConverter<EntryType, Integer> {
@Override
public final Integer convertToDatabaseColumn(EntryType attribute) {
return attribute.getIdentificador();
}
@Override
public final EntryType convertToEntityAttribute(Integer dbData) {
return EntryType.deIdentificador(dbData);
}
}
In your organization:
@Column(name = "type")
@Convert(converter=EntryTypeConverter.class)
private EntryType type;