Spring MVC Enum

1

I would like a help, I'm new to Spring MVC and I'm trying to send a numeral value of an Enum that I have in my class, but I'm not getting it, only the Nominal value is accepted.

I would like some help. Thanks

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
    
asked by anonymous 24.03.2016 / 00:09

3 answers

1

Not really. You are trying to pass a value that does not match the data type you declared. If you were using private Integer tipoCliente you would be able 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.

    
24.03.2016 / 00:22
0

I have a Personal Type enum that I use as below. In the entity class, I note the attribute with @Convert (convert = ConvertingPerspective), so:

@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);
        }

    }

}
    
12.01.2017 / 19:51
-1

You can use it as well

@Enumerated(EnumType.STRING)
    
21.09.2016 / 17:25