Spring MVC Enum

Asked

Viewed 808 times

1

I would like a help, I am new with Spring MVC and I am trying to send a numeral value of an Enum that I own in my class, but I am not succeeding, it is only accepted the Nominal value.

I’d like some help. Thank you

Example:

public enum TipoCliente 
{
    PessoaFisica,
    PessoaJuridica
}

class Clientes
{
@Column(nullable = false)
private TipoCliente tipoCliente;

//getters e setters
}

@RequestMapping(value = "/salvar", method = RequestMethod.POST)
public String salvar(Clientes cliente)
{
  clientesDAO.save(cliente);
}

<input type="text" name="tipoCliente" value="0"> <- Não aceita
<input type="text" name="tipoCliente" value="PessoaFisica"> <- Aceita

3 answers

1

You really don’t accept it. You are trying to pass a value that does not correspond to the type of data you have stated. If you were wearing private Integer tipoCliente it would be possible to pass the value you want since it is possible to convert from "0" to an Integer. Enums are much more powerful than routine use, take a look to understand a little better.

  • As for that I understood, but what I would really like to know is if there is no Annotation as in JPA to receive that Enum numeral? Thank you for your attention.

  • @Enumerated(EnumType.ORDINAL)&#xA; private TipoCliente tipoCliente; But I recommend using this approach carefully because it will be "stuck" to the enumeration order and other types may appear complicating the maintenance of the code in the future.

0

I have a Type Enum that I use the form below. Detail that in the entity class, I note the attribute with @Convert(convert = Typopessoaconverter), thus:

@Convert(converter = TipoPessoaConverter)
private TipoPessoa tipoPessa;

import java.util.stream.Stream;    
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;    
import lombok.Getter;

public enum TipoPessoa {

    PESSOA_FISICA("0"),
    PESSOA_JURIDICA("1");

    private final @Getter
    String code;

    /**
     * @param code
     */
    private TipoPessoa(String code) {
        this.code = code;
    }

    public static TipoPessoa getFromCode(String code) {
        return Stream.of(TipoPessoa.values())
                .filter(t -> t.getCode().equals(code))
                .findFirst()
                .orElse(null);
    }

    @Converter
    public static class TipoPessoaConverter implements AttributeConverter<TipoPessoa, String> {

        @Override
        public String convertToDatabaseColumn(TipoPessoa attribute) {
            return attribute.getCode();
        }

        @Override
        public TipoPessoa convertToEntityAttribute(String dbData) {
            return TipoPessoa.getFromCode(dbData);
        }

    }

}

-2

You can use it like this too

@Enumerated(EnumType.STRING)

Browser other questions tagged

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