Select Returning Null from Database

Asked

Viewed 633 times

1

I am trying to make a Login page and am using JaVA,JPA,WIldfly,Primefaces and in the database MYSQL.

I’m passing the name and password, but at the time of inspecting it returns me null, by playing the select in the database it selects perfectly.

LOGIN.XHTML

<!DOCTYPE html >
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets" template="template.xhtml">

    <ui:define name="conteudoForm">

        <h1>Login</h1>
        <p:spacer height="20" />
        <p:panelGrid columns="2" id="painelCadastro">
            <p:outputLabel value="Login" />
            <p:inputText id="inputLogin" value="#{loginMB.usuarios.login}" required="true" />
            <p:outputLabel value="Senha" />
            <p:password id="inputSenha" value="#{loginMB.usuarios.senha}" required="true"
                maxlength="7" />
        </p:panelGrid>
        <p:panelGrid>
            <p:commandButton value="Entrar" action="#{loginMB.doEfetuarLogin}" />
        </p:panelGrid>
    </ui:define>
</ui:composition>

USUARIO.DAO

package br.com.sicoob.DAO;

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

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import br.com.sicoob.Service.UsuariosService;
import br.com.sicoob.entidades.Usuarios;

@Stateless
public class UsuariosDAO implements Serializable, UsuariosService {

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


    @PersistenceContext
    private EntityManager em;

    /**
     * 
     * @param u
     */
    @Override
    public void remover(Usuarios u) {
        u = em.merge(u);
        em.remove(u);
    }

    /**
     * 
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<Usuarios> listarTodos() {
        List<Usuarios> usuarios = new ArrayList<Usuarios>();
        Query q = em.createQuery("select obj from Usuarios obj");
        usuarios = q.getResultList();
        return usuarios;
    }

    /**
     * 
     * @param id
     * @return
     */
    public Usuarios buscarPorId(Long id) {
        return em.find(Usuarios.class, id);
    }

    /**
     * 
     * @param u
     * @return
     */
    public Usuarios carregarEntidade(Usuarios u) {
        return em.merge(u);
    }

//  @Override
//  public void salvarUsuario(Usuarios usuario) {
//      if(usuario.getId() == null) {
//          em.persist(usuario);
//      } else {
//          em.merge(usuario);
//      }
//      
//  }
    @Override
    public Usuarios verificarUsuario(String nome, String senha) {
         try {
             Usuarios usuarios = (Usuarios) em.createQuery("SELECT nome , senha from usuarios where nome ='"+ nome +"' and senha ='"+ senha +"'").setParameter("nome", nome).setParameter("senha", senha).getSingleResult();

             return usuarios;
       } catch (Exception e) {
           System.out.println(e.getMessage());
             return null;
       }

    }



}

LOGIN.MB

package br.com.sicoob.ManagedBeans;

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

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import br.com.sicoob.DAO.UsuariosDAO;
import br.com.sicoob.Service.UsuariosService;
import br.com.sicoob.entidades.Usuarios;

@ManagedBean(name = "loginMB")
@SessionScoped
public class LoginMB {
    private Usuarios usuarios = new Usuarios();
    private List<Usuarios> listaUsuarios = new ArrayList<Usuarios>();
    private UsuariosDAO UsuariosDAO = new UsuariosDAO();

    @Inject
    private UsuariosService usuariosService;

    @PostConstruct
    public void init() {
        setListaUsuarios(usuariosService.listarTodos());
    }

    public String doEfetuarLogin() throws IOException {
         usuarios = UsuariosDAO.verificarUsuario(usuarios.getLogin(), usuarios.getSenha());
        if (usuarios == null) {
            usuarios = new Usuarios();
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuário não encontrado!", "Erro no Login!"));
            return null;
        } else {
            return "/main";
        }

    }

    public Usuarios getUsuarios() {
        return usuarios;
    }

    public void setUsuario(Usuarios usuarios) {
        this.usuarios = usuarios;
    }

    public List<Usuarios> getListaUsuarios() {
        return listaUsuarios;
    }

    public void setListaUsuarios(List<Usuarios> listaUsuarios) {
        this.listaUsuarios = listaUsuarios;
    }

}

Inspecting returns NULL:

inserir a descrição da imagem aqui

  • Check this out: http://stackoverflow.com/q/332365/540552

1 answer

2

Your query is wrong in:

 Usuarios usuarios = (Usuarios) em.createQuery("SELECT nome , senha from usuarios where nome ='"+ nome +"' and senha ='"+ senha+"'")
.setParameter("nome", nome).setParameter("senha", senha)
.getSingleResult();

Change to:

Usuarios usuarios = (Usuarios) em.createQuery("SELECT * from usuarios where nome = :nome and senha :senha")
.setParameter("nome", nome)
.setParameter("senha", senha)
.getSingleResult();

See more details here.

  • I changed the query, but it keeps coming Null

  • Your method listAll return data

  • I don’t understand your comment, can you explain to me again?

  • 1

    You have a public List<Users> listTodos() method, it returns something?

  • the list is being filled in correctly, coming from the right comic book!

  • Try to debug and take the login and password values and play straight into the type query "SELECT nome , senha from usuarios where nome ='joao'' and senha = '12345'" and see if it returns anything. something else you can do and take the cast from (Usuarios). leave Object usuarios = em.createQuery. and see what returns.

  • I used the following select :"SELECT name , password from usuarios Where name ='pedro' and password ='123'" it in the database works, but debugging it keeps giving null

  • 1
Show 3 more comments

Browser other questions tagged

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