How to define which data of an ENUM the JPA will persist in the bank?

Asked

Viewed 17 times

-1

Hello, I would like to know how to annotate a property (ID) of my ENUM for when to persist in the bank?

Because currently JPA is saving the index of the Enum array and not the ID... My Enum:

    @Getter
public enum SituacaoEnum {
    ABERTO(1, "Aberto"),
    EMEDICAO(2, "Em edicao"),
    FECHADO(3, "Fechado");

    Integer codigo;
    String marca;

    private Integer valor;

    MarcaBalcaoEnum(Integer valor, String marca) {

        this.valor = valor;
        this.marca = marca;

    }
}
  • You also have: https://answall.com/a/251747/112052

1 answer

0

You can use the annotation @Enumerated that has two options:

EnumType.STRING - Reads and saves the value of .name() of your Enum.

EnumType.ORDINAL- Reads and saves the value of .ordinal() of your Enum.

Remembering that the two options have the fragility that if you delete or reorder types, you may have inconsistency in the base.

If you want to save the code starting from 1, you can add as the first type of your Enum a code 0 that will not be used, because the method .ordinal() always starts from scratch.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.