How to persist the String of an Enumerator in the Database?

Asked

Viewed 711 times

2

I have the following Enumerator:

public enum ETipoCasa{

     Propria,
     Alugada,
     Financiada,
     Cedida;

}

And I’m trying to persist in the database the string of this enumerator as an example:

Casa casa = new Casa();
casa.setTipoCasa(ETipoCasa.Alugada);
casa.inserir();

I’m using Ibernate, recording in the bank the ordinal of Enum (1), and I wanted instead of the ordinal, to record the String (Rented). How do I do that?

  • What is the need to record string? if one day you change to Rented will give conflict.. Ai?

  • In Num you won’t change anything, names won’t, just order

2 answers

2

Try the javax.persistence annotation on the attribute being saved:

@Enumerated(Enumtype.STRING)

  • Mate, I’ve tried that way and it didn’t work.

  • @Tiagoferezin, but you recreated the bank table after trying the annotation?

  • Yes, I’ve recreated the table and nothing

2


James, the ideal would really be:

public enum ETipoCasa {
    Propria,
    Alugada,
    Financiada,
    Cedida;
}

public class Casa
{
    @Enumerated(EnumType.STRING)
    @Column(name = "tipo_casa")
    private ETipoCasa tipoCasa;

    public void setTipoCasa(String tipoCasa)
    {
        this.tipoCasa = tipoCasa;
    }
}

public static void main(String[] args)
{
    Casa casa = new Casa();
    casa.setTipoCasa(ETipoCasa.Alugada);
    casa.inserir();
}

Alternative: Kill the dove with a bazooka

Override the ENUM methods:

public enum ETipoCasa
{
    Propria ("Propria"),
    Alugada ("Alugada"),
    Financiada ("Financiada"),
    Cedida ("Cedida");

    private final String tipo_casa;

    private ETipoCasa(String s) {
        tipo_casa = s;
    }

    public boolean equalsName(String outroTipo)
    {
        return (outroTipo == null)? false : tipo_casa.equals(outroTipo);
    }

    public String toString()
    {
        return tipo_casa;
    }
}

public static void main(String[] args)
{
    Casa casa = new Casa();
    casa.setTipoCasa(ETipoCasa.Alugada);
    casa.inserir();
}

Browser other questions tagged

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