java.lang.IllegalArgumentException error in Hibernate when working with enum

6

Take a look at the error message:

jun 02, 2015 5:23:57 PM com.sun.faces.lifecycle.ApplyRequestValuesPhase execute
ADVERTÊNCIA: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
javax.el.ELException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:359)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:461)
    at org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:449)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1605)
    at org.hibernate.loader.Loader.getRow(Loader.java:1505)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:713)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:943)
    at org.hibernate.loader.Loader.doQuery(Loader.java:911)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2526)
    at org.hibernate.loader.Loader.doList(Loader.java:2512)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
    at org.hibernate.loader.Loader.list(Loader.java:2337)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:266)
    at com.algaworks.pedidovenda.repository.Clientes.porNome(Clientes.java:38)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean.completarCliente(CadastroPedidoBean.java:60)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean$Proxy$_$$_WeldClientProxy.completarCliente(CadastroPedidoBean$Proxy$_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 29 more

2015-06-02 17:23:57,353 ERROR [com.algaworks.pedidovenda.util.jsf.JsfExceptionHandler] Erro do sistema/WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
javax.faces.FacesException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:86)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: javax.el.ELException: /WEB-INF/template/pedidos/CapaPedido.xhtml @29,99 completeMethod="#{cadastroPedidoBean.completarCliente}": java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:111)
    at org.primefaces.component.autocomplete.AutoComplete.broadcast(AutoComplete.java:359)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
    at javax.faces.component.UIViewRoot.processDecodes(UIViewRoot.java:927)
    at com.sun.faces.lifecycle.ApplyRequestValuesPhase.execute(ApplyRequestValuesPhase.java:78)
    ... 25 more
Caused by: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]
    at org.hibernate.type.EnumType$NamedEnumValueMapper.fromName(EnumType.java:461)
    at org.hibernate.type.EnumType$NamedEnumValueMapper.getValue(EnumType.java:449)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:107)
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:127)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:106)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1605)
    at org.hibernate.loader.Loader.getRow(Loader.java:1505)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:713)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:943)
    at org.hibernate.loader.Loader.doQuery(Loader.java:911)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
    at org.hibernate.loader.Loader.doList(Loader.java:2526)
    at org.hibernate.loader.Loader.doList(Loader.java:2512)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
    at org.hibernate.loader.Loader.list(Loader.java:2337)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:495)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:356)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
    at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:266)
    at com.algaworks.pedidovenda.repository.Clientes.porNome(Clientes.java:38)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean.completarCliente(CadastroPedidoBean.java:60)
    at com.algaworks.pedidovenda.controller.CadastroPedidoBean$Proxy$_$$_WeldClientProxy.completarCliente(CadastroPedidoBean$Proxy$_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:245)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
    at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    ... 29 more

As far as I understand the error is in the client-complete method.

Class CadastroPedidoBean :

package com.algaworks.pedidovenda.controller;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.algaworks.pedidovenda.model.Cliente;
import com.algaworks.pedidovenda.model.EnderecoEntrega;
import com.algaworks.pedidovenda.model.FormaPagamento;
import com.algaworks.pedidovenda.model.Pedido;
import com.algaworks.pedidovenda.model.Usuario;
import com.algaworks.pedidovenda.repository.Clientes;
import com.algaworks.pedidovenda.repository.Usuarios;
import com.algaworks.pedidovenda.service.NegocioException;
import com.algaworks.pedidovenda.util.jsf.FacesUtil;

@Named
@ViewScoped
public class CadastroPedidoBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Inject
    private Usuarios usuarios;

    @Inject
    private Clientes clientes;

    private Pedido pedido;

    private List<Usuario> vendedores;

    public CadastroPedidoBean() {
        limpar();
    }

    public void inicializar(){
        if(FacesUtil.isNotPosBack()){
            this.vendedores = usuarios.vendedores();
        }
    }

    public void limpar() {
        pedido = new Pedido();
        pedido.setEnderecoEntrega(new EnderecoEntrega());
    }
//  
//  public FormaPagamento[] getFormasPagamento() {
//      return FormaPagamento.values();
//  }


    public List<Cliente> completarCliente(String nome){
        return this.clientes.porNome(nome);
    }

    public void salvar() {
        throw new NegocioException(
                "Pedido não foi salvo, pois ainda não foi implementado");
    }

    public Pedido getPedido() {
        return pedido;
    }

    public void setPedido(Pedido pedido) {
        this.pedido = pedido;
    }

    public List<Usuario> getVendedores() {
        return vendedores;
    }

    public void setVendedores(List<Usuario> vendedores) {
        this.vendedores = vendedores;
    }

}

Client class that is in the repository:

package com.algaworks.pedidovenda.repository;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import com.algaworks.pedidovenda.model.Cliente;

public class Clientes implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Cliente porId(Long id) {
        return this.manager.find(Cliente.class, id);
    }


    public List<Cliente> porNome(String nome) {
        return this.manager.createQuery("from Cliente " +
                "where upper(nome) like :nome", Cliente.class)
                .setParameter("nome", nome.toUpperCase() + "%")
                .getResultList();
    }

}

This is my Client entity;

package com.algaworks.pedidovenda.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "cliente")
public class Cliente implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String nome;
    private String email;
    private String documentoReceitaFederal;
    private TipoPessoa tipo;
    private List<Endereco> enderecos = new ArrayList<>();

    @Id
    @GeneratedValue
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(nullable = false, length = 100)
    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    @Column(nullable = false, length = 255)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "doc_receita_federal", nullable = false, length = 14)
    public String getDocumentoReceitaFederal() {
        return documentoReceitaFederal;
    }

    public void setDocumentoReceitaFederal(String documentoReceitaFederal) {
        this.documentoReceitaFederal = documentoReceitaFederal;
    }

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 10)
    public TipoPessoa getTipo() {
        return tipo;
    }

    public void setTipo(TipoPessoa tipo) {
        this.tipo = tipo;
    }

    @OneToMany(mappedBy = "cliente", cascade = CascadeType.ALL)
    public List<Endereco> getEnderecos() {
        return enderecos;
    }

    public void setEnderecos(List<Endereco> enderecos) {
        this.enderecos = enderecos;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Cliente other = (Cliente) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

}

And this is my class enum TypePerson

package com.algaworks.pedidovenda.model;

public enum TipoPessoa {

    FISICA, JURIDICA

}
    
asked by anonymous 02.06.2015 / 22:28

1 answer

5

Here's your error message:

Caused by: java.lang.IllegalArgumentException: Unknown name value [fisica] for enum class [com.algaworks.pedidovenda.model.TipoPessoa]

This is your enum:

package com.algaworks.pedidovenda.model;

public enum TipoPessoa {

    FISICA, JURIDICA

}

Notice the difference between uppercase and lowercase letters. fisica and FISICA are different!

Where did fisica come from? Apparently this is what is saved in the database:

at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1673)

So, I have three suggestions. Choose one:

  • Rotate a UPDATE cliente SET tipo = 'FISICA' WHERE tipo = 'fisica' in your database.

  • Change enum to fisica instead of FISICA .

  • Change the mapping to String , but expose only the methods that work with TipoPessoa :

  •     private String tipo;
    
        @Transient
        public TipoPessoa getTipo() {
            return tipo == null ? null : TipoPessoa.valueOf(tipo.toUpperCase(Locale.ROOT));
        }
    
        public void setTipo(TipoPessoa tipo) {
            this.tipo = tipo == null ? null : tipo.name();
        }
    
        @Column(nullable = false, length = 10, name = "tipo")
        protected String getTipoString() {
            return tipo;
        }
    
        protected void setTipoString(String tipo) {
            this.tipo = tipo;
        }
    
        
    02.06.2015 / 23:14