Erro ao fazer busca no banco de dados mysql + jsf + hibernate(Resolvido)

25 respostas
Dfodani

ola tudo bem ? nao estou conseguindo fazer a busca no banco de dados alguem pode me ajudar implementei todos os codigos mas da erro?

Classe ClienteBean

package br.com.mjailton.vendasjsf.bean;

import java.util.List;

import javax.faces.bean.ManagedBean;

import javax.persistence.EntityManager;

import javax.persistence.Query;

import br.com.mjailton.vendasjsf.modelo.Cliente;
import br.com.mjailton.vendasjsf.util.JPAUtil;

@ManagedBean

public class ClienteBean {

private Cliente cliente = new Cliente();
private List<Cliente> clientes;

public void salva(){
	
	EntityManager em = new JPAUtil().getEntityManager();
	em.getTransaction().begin();
	em.persist(cliente);
	em.getTransaction().commit();
	em.close();
	
}


public void excluir(Cliente cliente){
	
	EntityManager em = new JPAUtil().getEntityManager();
	em.getTransaction().begin();
	cliente = em.merge(cliente);
	em.remove(cliente);
	em.getTransaction().commit();
	em.close();
	
}

public List<Cliente> getClientes(){
	if(this.clientes==null) {
	EntityManager em = new JPAUtil().getEntityManager();
	Query q = em.createQuery("SELECT c FROM Cliente c" , Cliente.class);
	this.clientes = q.getResultList();
	em.close();
	}
	return clientes;
	
}
 public List buscarClientePorNome(Cliente cliente) {
	 EntityManager em = new JPAUtil().getEntityManager();
        Query query = em.createQuery("select u from Cliente u where nome like :nome");
        query.setParameter("nome", cliente.getNome());
        this.clientes = query.getResultList();
        if (clientes.isEmpty()) {
            return null;
        }
        return clientes;
    }
    public List getBuscaClientes() {
        return buscarClientePorNome(cliente);
    }



public Cliente getCliente() {
	return cliente;
}


public void setCliente(Cliente cliente) {
	this.cliente = cliente;
}

}

Classe Cliente

package br.com.mjailton.vendasjsf.modelo;

import java.util.Date;
import java.util.List;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import <a href="http://javax.persistence.Id">javax.persistence.Id</a>;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

@Entity
public class Cliente {

@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name=id_cliente)

private Long idCliente;

private String nome;

private String endereco;

private String cpf;

private String bairro;

private String cidade;

private String uf;

private String cep;

private String telefone;

private String complemento;

private String rg;

private String email;
public String getEndereco() {

return endereco;

}

public void setEndereco(String endereco) {

this.endereco = endereco;

}

public String getCpf() {

return cpf;

}

public void setCpf(String cpf) {

this.cpf = cpf;

}

public String getBairro() {

return bairro;

}

public void setBairro(String bairro) {

this.bairro = bairro;

}

public String getCidade() {

return cidade;

}

public void setCidade(String cidade) {

this.cidade = cidade;

}

public String getUf() {

return uf;

}

public void setUf(String uf) {

this.uf = uf;

}

public String getCep() {

return cep;

}

public void setCep(String cep) {

this.cep = cep;

}

public String getTelefone() {

return telefone;

}

public void setTelefone(String telefone) {

this.telefone = telefone;

}

public String getComplemento() {

return complemento;

}

public void setComplemento(String complemento) {

this.complemento = complemento;

}

public String getRg() {

return rg;

}

public void setRg(String rg) {

this.rg = rg;

}
public Long getIdCliente() {

return idCliente;

}

public void setIdCliente(Long id_cliente) {

this.idCliente = id_cliente;

}

public String getNome() {

return nome;

}

public void setNome(String cliente) {

this.nome = cliente;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

}

Classe Consultar Cliente

<?xml version="1.0" encoding="ISO-8859-1" ?> Controle de Usuários
<h:form>
                        <table width="500" align="center">
                            <tr>
                                <td colspan="2" align="right"><h:outputText value="Informe o nome do usuário a ser pesquisado" /></td>
                            </tr>
                            <tr>
                                <td align="right"><h:inputText  value="#{clienteBean.cliente.nome}" /></td>
                                <td align="left"><h:commandButton value="Pesquisar" action="#{clienteBean.buscarClientePorNome(cliente)}"></h:commandButton></td>
                            </tr>
                        </table>
                        <br /><br /><br />
                        <!--Início tabela de lista-->
                               <h:dataTable value="#{clienteBean.clientes}" var="cliente" styleClass="orders" headerClass="ordersHeader" columnClasses="oddColumn" rowClasses=" eveRow, oddRow">
                            <h:column>
                                <f:facet name="header">
                                    Nome:
                                </f:facet>
                                #{cliente.nome}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Endereço:
                                </f:facet>
                                #{cliente.endereco}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cpf
                                </f:facet>
                                #{cliente.cpf}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Bairro:
                                </f:facet>
                                #{cliente.bairro}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cidade
                                </f:facet>
                                #{cliente.cidade}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Uf
                                </f:facet>
                                #{cliente.uf}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cep
                                </f:facet>
                                #{cliente.cep}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Telefone
                                </f:facet>
                                #{cliente.telefone}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Complemento
                                </f:facet>
                                #{cliente.complemento}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Rg
                                </f:facet>
                                #{cliente.rg}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Email
                                </f:facet>
                                #{cliente.email}
                            </h:column>
                        </h:dataTable> <!--Fim tabela de lista--> 
                    </h:form>
</h:body>

25 Respostas

Dfodani

erro

HTTP Status 500 – Internal Server Error
Type Exception Report

Message java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: java.lang.NullPointerException

javax.faces.webapp.FacesServlet.service(FacesServlet.java:671)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause
javax.faces.el.EvaluationException: java.lang.NullPointerException

javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)

com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

javax.faces.component.UICommand.broadcast(UICommand.java:315)

javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause
java.lang.NullPointerException

br.com.mjailton.vendasjsf.bean.ClienteBean.buscarClientePorNome(ClienteBean.java:53)

sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

java.lang.reflect.Method.invoke(Unknown Source)

org.apache.el.parser.AstValue.invoke(AstValue.java:247)

org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)

com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)

javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)

com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

javax.faces.component.UICommand.broadcast(UICommand.java:315)

javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/9.0.14

Villagram

Boa noite amiga.

Você precisa terminar de fazer o mapeamento da sua classe de entidade e também colocar o hashcode, equals e toString, deve ser essa a causa do NullPointer. Implementar Serializable tbm é necessário para uso em Servlets.

@Entity
public class Cliente implements Serializable{

    private static final long serialVersionUID = -6708700734432227805L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_cliente")
    private Long idCliente;
    @Column(name = "nome")
    private String nome;
    @Column(name = "endereco")
    private String endereco;
    @Column(name = "cpf")
    private String cpf;
    @Column(name = "bairro")
    private String bairro;
    @Column(name = "cidade")
    private String cidade;
    @Column(name = "uf")
    private String uf;
    @Column(name = "cep")
    private String cep;
    @Column(name = "telefone")
    private String telefone;
    @Column(name = "complemento")
    private String complemento;
    @Column(name = "rg")
    private String rg;
    @Column(name = "email")
    private String email;

    //Getters and Setters

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 17 * hash + Objects.hashCode(this.idCliente);
        hash = 17 * hash + Objects.hashCode(this.nome);
        hash = 17 * hash + Objects.hashCode(this.endereco);
        hash = 17 * hash + Objects.hashCode(this.cpf);
        hash = 17 * hash + Objects.hashCode(this.bairro);
        hash = 17 * hash + Objects.hashCode(this.cidade);
        hash = 17 * hash + Objects.hashCode(this.uf);
        hash = 17 * hash + Objects.hashCode(this.cep);
        hash = 17 * hash + Objects.hashCode(this.telefone);
        hash = 17 * hash + Objects.hashCode(this.complemento);
        hash = 17 * hash + Objects.hashCode(this.rg);
        hash = 17 * hash + Objects.hashCode(this.email);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
            final Cliente other = (Cliente) obj;
        if (!Objects.equals(this.nome, other.nome)) {
            return false;
        }
        if (!Objects.equals(this.endereco, other.endereco)) {
            return false;
        }
        if (!Objects.equals(this.cpf, other.cpf)) {
            return false;
        }
        if (!Objects.equals(this.bairro, other.bairro)) {
            return false;
        }
        if (!Objects.equals(this.cidade, other.cidade)) {
            return false;
        }
        if (!Objects.equals(this.uf, other.uf)) {
            return false;
        }
        if (!Objects.equals(this.cep, other.cep)) {
            return false;
        }
        if (!Objects.equals(this.telefone, other.telefone)) {
            return false;
        }
        if (!Objects.equals(this.complemento, other.complemento)) {
            return false;
        }
        if (!Objects.equals(this.rg, other.rg)) {
            return false;
        }
        if (!Objects.equals(this.email, other.email)) {
            return false;
        }
        if (!Objects.equals(this.idCliente, other.idCliente)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "Cliente{" + "idCliente=" + idCliente + ", nome=" + nome + ", endereco=" + endereco + ", cpf=" + cpf + ", bairro=" + bairro + ", cidade=" + cidade + ", uf=" + uf + ", cep=" + cep + ", telefone=" + telefone + ", complemento=" + complemento + ", rg=" + rg + ", email=" + email + '}';
    }

}

Espero que isso ajude; :metal::sunglasses::metal:

Dfodani
package br.com.mjailton.vendasjsf.modelo;
import java.io.Serializable;

import java.util.Date;

import java.util.List;
import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import <a href="http://javax.persistence.Id">javax.persistence.Id</a>;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

@Entity
public class Cliente implements Serializable{

private static final long serialVersionUID = -6708700734432227805L;
@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name=id_cliente)

private Long idCliente;

private String nome;

private String endereco;

private String cpf;

private String bairro;

private String cidade;

private String uf;

private String cep;

private String telefone;

private String complemento;

private String rg;

private String email;
public static long getSerialversionuid() {

return serialVersionUID;

}

public String getEndereco() {

return endereco;

}

public void setEndereco(String endereco) {

this.endereco = endereco;

}

public String getCpf() {

return cpf;

}

public void setCpf(String cpf) {

this.cpf = cpf;

}

public String getBairro() {

return bairro;

}

public void setBairro(String bairro) {

this.bairro = bairro;

}

public String getCidade() {

return cidade;

}

public void setCidade(String cidade) {

this.cidade = cidade;

}

public String getUf() {

return uf;

}

public void setUf(String uf) {

this.uf = uf;

}

public String getCep() {

return cep;

}

public void setCep(String cep) {

this.cep = cep;

}

public String getTelefone() {

return telefone;

}

public void setTelefone(String telefone) {

this.telefone = telefone;

}

public String getComplemento() {

return complemento;

}

public void setComplemento(String complemento) {

this.complemento = complemento;

}

public String getRg() {

return rg;

}

public void setRg(String rg) {

this.rg = rg;

}
public Long getIdCliente() {

return idCliente;

}

public void setIdCliente(Long id_cliente) {

this.idCliente = id_cliente;

}

public String getNome() {

return nome;

}

public void setNome(String cliente) {

this.nome = cliente;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

<a class="mention" href="/u/override">@Override</a>

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((bairro == null) ? 0 : bairro.hashCode());

result = prime * result + ((cep == null) ? 0 : cep.hashCode());

result = prime * result + ((cidade == null) ? 0 : cidade.hashCode());

result = prime * result + ((complemento == null) ? 0 : complemento.hashCode());

result = prime * result + ((cpf == null) ? 0 : cpf.hashCode());

result = prime * result + ((email == null) ? 0 : email.hashCode());

result = prime * result + ((endereco == null) ? 0 : endereco.hashCode());

result = prime * result + ((idCliente == null) ? 0 : idCliente.hashCode());

result = prime * result + ((nome == null) ? 0 : nome.hashCode());

result = prime * result + ((rg == null) ? 0 : rg.hashCode());

result = prime * result + ((telefone == null) ? 0 : telefone.hashCode());

result = prime * result + ((uf == null) ? 0 : uf.hashCode());

return result;

}

<a class="mention" href="/u/override">@Override</a>

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 (bairro == null) {

if (other.bairro != null)

return false;

} else if (!bairro.equals(other.bairro))

return false;

if (cep == null) {

if (other.cep != null)

return false;

} else if (!cep.equals(other.cep))

return false;

if (cidade == null) {

if (other.cidade != null)

return false;

} else if (!cidade.equals(other.cidade))

return false;

if (complemento == null) {

if (other.complemento != null)

return false;

} else if (!complemento.equals(other.complemento))

return false;

if (cpf == null) {

if (other.cpf != null)

return false;

} else if (!cpf.equals(other.cpf))

return false;

if (email == null) {

if (other.email != null)

return false;

} else if (!email.equals(other.email))

return false;

if (endereco == null) {

if (other.endereco != null)

return false;

} else if (!endereco.equals(other.endereco))

return false;

if (idCliente == null) {

if (other.idCliente != null)

return false;

} else if (!idCliente.equals(other.idCliente))

return false;

if (nome == null) {

if (other.nome != null)

return false;

} else if (!nome.equals(other.nome))

return false;

if (rg == null) {

if (other.rg != null)

return false;

} else if (!rg.equals(other.rg))

return false;

if (telefone == null) {

if (other.telefone != null)

return false;

} else if (!telefone.equals(other.telefone))

return false;

if (uf == null) {

if (other.uf != null)

return false;

} else if (!uf.equals(other.uf))

return false;

return true;

}

<a class="mention" href="/u/override">@Override</a>

public String toString() {

return “Cliente [idCliente=” + idCliente + “, nome=” + nome + “, endereco=” + endereco + “, cpf=” + cpf

+ “, bairro=” + bairro + “, cidade=” + cidade + “, uf=” + uf + “, cep=” + cep + “, telefone=” + telefone

+ “, complemento=” + complemento + “, rg=” + rg + “, email=” + email + “]”;

}

}

nao deu certo

Villagram

Você colocou todo o mapeamento da classe? Não está aparecendo o mapeando das colunas no seu post.

Dfodani

vou tentar vamos ver

Villagram

Outra coisa que pode estar acontecendo é o método de busca, se não tiver nenhum registro no seu banco de dados vai dar nullpointer mesmo.

public List buscarClientePorNome(Cliente cliente) {
    EntityManager em = new JPAUtil().getEntityManager();
    Query query = em.createQuery("select u from Cliente u where nome like :nome");
    query.setParameter("nome", cliente.getNome());
    //Retorna null se não tiver retorno de registros, por isso não tem lista para verificar nulidade
    this.clientes = query.getResultList();
    //essa verificação evita nullpointer
    if (clientes != null) {
        return clientes;
    }
    return null;
}
Villagram

Verifique tbm se você declarou a classe Cliente no seu persistence.xml, muita gente esquece disto.

Dfodani
jan 20, 2019 10:27:04 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute

ADVERTÊNCIA: #{clienteBean.buscarClientePorNome(cliente)}: java.lang.NullPointerException

javax.faces.FacesException: #{clienteBean.buscarClientePorNome(cliente)}: java.lang.NullPointerException

at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)

at javax.faces.component.UICommand.broadcast(UICommand.java:315)

at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)

at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

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.faces.el.EvaluationException: java.lang.NullPointerException

at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)

at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

 29 more

Caused by: java.lang.NullPointerException

at br.com.mjailton.vendasjsf.bean.ClienteBean.buscarClientePorNome(ClienteBean.java:54)

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:247)

at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)

at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)

at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)

 30 more
jan 20, 2019 10:27:04 PM org.apache.catalina.core.StandardWrapperValve invoke

GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/vendas] threw exception [java.lang.NullPointerException] with root cause

java.lang.NullPointerException

at br.com.mjailton.vendasjsf.bean.ClienteBean.buscarClientePorNome(ClienteBean.java:54)

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:247)

at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)

at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)

at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)

at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

at javax.faces.component.UICommand.broadcast(UICommand.java:315)

at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)

at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)

at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)

at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)

at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)

at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)

at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)

at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)

at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)

at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)

at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)

at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)

at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)

at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)

at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)

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)

deu esse erro

e tem registro sim

eu ja alterei a classe

Villagram

Olhando o erro parece ser um problema na implementação da consulta, mas para saber se é isso mesmo só fazendo o debug.

Dfodani

mais erros

HTTP Status 500 – Internal Server Error
Type Exception Report

Message java.lang.NullPointerException

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: java.lang.NullPointerException

javax.faces.webapp.FacesServlet.service(FacesServlet.java:671)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause
javax.faces.el.EvaluationException: java.lang.NullPointerException

javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)

com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

javax.faces.component.UICommand.broadcast(UICommand.java:315)

javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Root Cause
java.lang.NullPointerException

br.com.mjailton.vendasjsf.bean.ClienteBean.buscarClientePorNome(ClienteBean.java:54)

sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

java.lang.reflect.Method.invoke(Unknown Source)

org.apache.el.parser.AstValue.invoke(AstValue.java:247)

org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)

com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)

javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)

com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)

javax.faces.component.UICommand.broadcast(UICommand.java:315)

javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)

javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)

com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)

com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)

com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)

javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)

org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/9.0.14

postarei as classes novamente alteradas:

método do bean buscar eu so estou fazendo a busca por este metodo

public List buscarClientePorNome(Cliente cliente) {
EntityManager em = new JPAUtil().getEntityManager();
Query query = em.createQuery(“select u from Cliente u where nome like :nome”);
query.setParameter(“nome”, cliente.getNome());
//Retorna null se não tiver retorno de registros, por isso não tem lista para verificar nulidade
this.clientes = query.getResultList();
//essa verificação evita nullpointer
if (clientes != null) {
return clientes;
}
return null;
}

Classe Cliente alterada

package br.com.mjailton.vendasjsf.modelo;

import java.io.Serializable;

import java.util.Date;

import java.util.List;
import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import <a href="http://javax.persistence.Id">javax.persistence.Id</a>;

import javax.persistence.ManyToOne;

import javax.persistence.OneToMany;

import javax.persistence.Temporal;

import javax.persistence.TemporalType;

@Entity
public class Cliente implements Serializable {

private static final long serialVersionUID = -6708700734432227805L;
@Id

@GeneratedValue(strategy=GenerationType.IDENTITY)

@Column(name=id_cliente)

private Long idCliente;

@Column(name = nome)

private String nome;

@Column(name = endereco)

private String endereco;

@Column(name = cpf)

private String cpf;

@Column(name = bairro)

private String bairro;

@Column(name = cidade)

private String cidade;

@Column(name = uf)

private String uf;

@Column(name = cep)

private String cep;

@Column(name = telefone)

private String telefone;

@Column(name = complemento)

private String complemento;

@Column(name = rg)

private String rg;

@Column(name = email)

private String email;
public static long getSerialversionuid() {

return serialVersionUID;

}

public String getEndereco() {

return endereco;

}

public void setEndereco(String endereco) {

this.endereco = endereco;

}

public String getCpf() {

return cpf;

}

public void setCpf(String cpf) {

this.cpf = cpf;

}

public String getBairro() {

return bairro;

}

public void setBairro(String bairro) {

this.bairro = bairro;

}

public String getCidade() {

return cidade;

}

public void setCidade(String cidade) {

this.cidade = cidade;

}

public String getUf() {

return uf;

}

public void setUf(String uf) {

this.uf = uf;

}

public String getCep() {

return cep;

}

public void setCep(String cep) {

this.cep = cep;

}

public String getTelefone() {

return telefone;

}

public void setTelefone(String telefone) {

this.telefone = telefone;

}

public String getComplemento() {

return complemento;

}

public void setComplemento(String complemento) {

this.complemento = complemento;

}

public String getRg() {

return rg;

}

public void setRg(String rg) {

this.rg = rg;

}
public Long getIdCliente() {

return idCliente;

}

public void setIdCliente(Long id_cliente) {

this.idCliente = id_cliente;

}

public String getNome() {

return nome;

}

public void setNome(String cliente) {

this.nome = cliente;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

<a class="mention" href="/u/override">@Override</a>

public int hashCode() {

final int prime = 31;

int result = 1;

result = prime * result + ((bairro == null) ? 0 : bairro.hashCode());

result = prime * result + ((cep == null) ? 0 : cep.hashCode());

result = prime * result + ((cidade == null) ? 0 : cidade.hashCode());

result = prime * result + ((complemento == null) ? 0 : complemento.hashCode());

result = prime * result + ((cpf == null) ? 0 : cpf.hashCode());

result = prime * result + ((email == null) ? 0 : email.hashCode());

result = prime * result + ((endereco == null) ? 0 : endereco.hashCode());

result = prime * result + ((idCliente == null) ? 0 : idCliente.hashCode());

result = prime * result + ((nome == null) ? 0 : nome.hashCode());

result = prime * result + ((rg == null) ? 0 : rg.hashCode());

result = prime * result + ((telefone == null) ? 0 : telefone.hashCode());

result = prime * result + ((uf == null) ? 0 : uf.hashCode());

return result;

}

<a class="mention" href="/u/override">@Override</a>

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 (bairro == null) {

if (other.bairro != null)

return false;

} else if (!bairro.equals(other.bairro))

return false;

if (cep == null) {

if (other.cep != null)

return false;

} else if (!cep.equals(other.cep))

return false;

if (cidade == null) {

if (other.cidade != null)

return false;

} else if (!cidade.equals(other.cidade))

return false;

if (complemento == null) {

if (other.complemento != null)

return false;

} else if (!complemento.equals(other.complemento))

return false;

if (cpf == null) {

if (other.cpf != null)

return false;

} else if (!cpf.equals(other.cpf))

return false;

if (email == null) {

if (other.email != null)

return false;

} else if (!email.equals(other.email))

return false;

if (endereco == null) {

if (other.endereco != null)

return false;

} else if (!endereco.equals(other.endereco))

return false;

if (idCliente == null) {

if (other.idCliente != null)

return false;

} else if (!idCliente.equals(other.idCliente))

return false;

if (nome == null) {

if (other.nome != null)

return false;

} else if (!nome.equals(other.nome))

return false;

if (rg == null) {

if (other.rg != null)

return false;

} else if (!rg.equals(other.rg))

return false;

if (telefone == null) {

if (other.telefone != null)

return false;

} else if (!telefone.equals(other.telefone))

return false;

if (uf == null) {

if (other.uf != null)

return false;

} else if (!uf.equals(other.uf))

return false;

return true;

}

<a class="mention" href="/u/override">@Override</a>

public String toString() {

return “Cliente [idCliente=” + idCliente + “, nome=” + nome + “, endereco=” + endereco + “, cpf=” + cpf

+ “, bairro=” + bairro + “, cidade=” + cidade + “, uf=” + uf + “, cep=” + cep + “, telefone=” + telefone

+ “, complemento=” + complemento + “, rg=” + rg + “, email=” + email + “]”;

}

}

Formulário Consulta Cliente

<?xml version="1.0" encoding="ISO-8859-1" ?>

Controle de Usuários
<h:form>
                        <table width="500" align="center">
                            <tr>
                                <td colspan="2" align="right"><h:outputText value="Informe o nome do usuário a ser pesquisado" /></td>
                            </tr>
                            <tr>
                                <td align="right"><h:inputText  value="#{clienteBean.cliente.nome}" /></td>
                                <td align="left"><h:commandButton value="Pesquisar" action="#{clienteBean.buscarClientePorNome(cliente)}"></h:commandButton></td>
                            </tr>
                        </table>
                        <br /><br /><br />
                        <!--Início tabela de lista-->
                               <h:dataTable value="#{clienteBean.clientes}" var="cliente" styleClass="orders" headerClass="ordersHeader" columnClasses="oddColumn" rowClasses=" eveRow, oddRow">
                            <h:column>
                                <f:facet name="header">
                                    Nome:
                                </f:facet>
                                #{cliente.nome}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Endereço:
                                </f:facet>
                                #{cliente.endereco}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cpf
                                </f:facet>
                                #{cliente.cpf}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Bairro:
                                </f:facet>
                                #{cliente.bairro}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cidade
                                </f:facet>
                                #{cliente.cidade}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Uf
                                </f:facet>
                                #{cliente.uf}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Cep
                                </f:facet>
                                #{cliente.cep}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Telefone
                                </f:facet>
                                #{cliente.telefone}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Complemento
                                </f:facet>
                                #{cliente.complemento}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Rg
                                </f:facet>
                                #{cliente.rg}
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    Email
                                </f:facet>
                                #{cliente.email}
                            </h:column>
                        </h:dataTable> <!--Fim tabela de lista--> 
                    </h:form>
</h:body>
Villagram

Você está usando o tomcat como containner da sua aplicação?

Dfodani

sim ainda nao sei qual erro é esse ele lista do banco mas na hora que vc digita o nome pra pesquisar ele nao busca acaba que dando esse erro parece que é no metodo

Dfodani

sim

Dfodani

to usando mysql tbm

Villagram

Posso fazer o debug para você via teamviewer e postar a resposta aqui depois, pois reconstruir a aplicação por aqui demandaria muito trabalho.

Dfodani

tenho que baixar o teamviewer ainda

Villagram

Sem problemas, pode me contactar por email: [email removido]

Dfodani

sera que nao é aqui o erro?

Dfodani
Dfodani

<h:commandButton value=“Pesquisar” action="#{clienteBean.buscarClientePorNome(cliente)}"></h:commandButton>

Villagram

Boa noite…

Realmente esse é o erro…nem tinha percebido que você não tem um controller, vou dar uma olhada melhor no código assim que puder. Pensei que você estava somente testando a classe de pesquisa.

Dfodani

agora foi
resolvi assim

public List busca(){

EntityManager em = new JPAUtil().getEntityManager();

Query q = em.createQuery(select u from Cliente u where nome like :nome”, Cliente.class);

q.setParameter(nome”, cliente.getNome());

this.clientes = q.getResultList();

em.close();

return clientes;

}
Dfodani

estou testando rsrs ainda tenho que criar e alterar mta coisa rs

Dfodani

to tentando passar uma aplicação minha pra web sou iniciante ainda mas to felizz de aprender jsf pq nao passei em uma entrevista por isso

Villagram

Que bom que conseguiu resolver seu problema. Passar uma aplicação pra web não é tarefa fácil, te desejo sorte e sempre que precisar podemos nos ajudar. Acho o conteúdo da algaworks muito bom para quem quer usar jsf, procure sobre primefaces.

Criado 20 de janeiro de 2019
Ultima resposta 21 de jan. de 2019
Respostas 25
Participantes 2