Error in web system authentication

Asked

Viewed 305 times

1

I’m learning together with a tutorial to develop a petshop system and I’m getting the following hibernate error:

Hibernate: selectcliente0_.idClient as idClient2_2_, cliente0_.email as email3_2_, cliente0_.name as name4_2_, cliente0_.password as password5_2_, cliente0_.tipo as tip1_2_ from Client cliente0_ left Outer Join PFcliente0_1_ on cliente0_.idCliente=cliente0_1_.idCliente left Outer Join PJ cliente0_2_ on cliente0_.idCliente=cliente0_2_.idCliente Where cliente0_.email=? and cliente0_.password=? Error in authentication

Method authenticate (Clientemtd class):

public static Autenticavel autenticar(String usuario, String senha) {
    Session session = HibernateUtil.getInstance();
    Transaction tx = null;
    Cliente p = null;
    try {
        Query q;
        tx = session.beginTransaction();
        q = session.createQuery("FROM Cliente as p where p.email=:usuario and p.senha=:senha");
        q.setParameter("usuario", usuario);
        q.setParameter("senha", senha);
        List resultados = q.list();
        if (resultados.size() > 0) {
            p = (Cliente) resultados.get(0);
        }
        return p;
    } catch (Exception e) {
        tx.rollback();
        e.printStackTrace();
        return p;
    } finally {
        session.close();
    }
}

Authenticatable.java:

package br.com.diego.controle;

public interface Autenticavel {

public Autenticavel autenticar(String usuario, String senha);

public boolean existe(String usuario);
}

Testandohibernate.java:

public class TestandoHibernate {

public static void main(String[] args) {

    GerarTabelas();
    if (autenticar("[email protected]", "root") != null) {
        System.out.println("Usuário autenticado");
    } else {
        System.out.println("Erro na autenticação");
    }
    try {
        persistindo();
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Erro" + ex.getMessage());
    }
}

 public static Autenticavel autenticar(String usuario, String senha) {
    return new PF().autenticar(usuario, senha);
}

private static void persistindo() throws Exception {
    PF pf = new PF();
    pf.setNome("Diego Juarez");
    pf.setEmail("[email protected]");
    pf.setSenha("root");
    DocReceita CPF = new CPF(" 122. 379. 567-58 ");
    pf.setDocReceita(CPF);
    CPF.setCliente(pf);

    if (pf.existe(CPF) == true) {
        throw new RuntimeException("<br><center><font face='verdana' color='red'   size='2'><br />já existe usuário cadastrado com o CPF ou CNPJ informado</font></center><br>");
    }

    Endereco end = new Endereco();
    end.setBairro("Centro");
    end.setCep("28610175");
    end.setCidade("Nova Friburgo");
    end.setLograd("Pca Presidente Getulio Vargas 220");
    end.setNumero("402");
    end.setUf("RJ");
    end.setCliente(pf);

    Collection<Endereco> e = new ArrayList<Endereco>();
    e.add(end);
    pf.setEndereco(e);

    Telefone t = new Telefone();
    t.setCodArea(21);
    t.setNumero("988336760");
    t.setCliente(pf);

    Collection<Telefone> tel = new ArrayList<Telefone>();
    tel.add(t);
    pf.setTelefone(tel);

    Pet a = new Cachorro();
    Date d = new Date(2010, 04, 26);
    a.setDataNascimento(d);
    a.setNome("Rex");
    a.setRaca("Bulldog");
    a.setSexo('M');
    a.setObs("Peida muito!");
    a.setCliente(pf);

    Servico s = new Consulta();
    s.setData(new Date());
    s.setDescricao("Problema de peso");
    s.setValor(20);
    s.setPet(a);

    Collection<Servico> serv = new ArrayList<Servico>();
    serv.add(s);
    a.setServico(serv);

    Collection<Pet> peti = new ArrayList<Pet>();
    peti.add(a);
    pf.setPet(peti);

    PF.salvar(pf);
}    
}

Can anyone help me find the error? Thanks in advance!

Hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
 <!-- Database connection settings -->

    <property name="connection.url">jdbc:mysql://localhost:3306/petshop1</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.username">root</property>
    <property name="connection.password">6452software</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">10</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>


    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">update</property>

<mapping class="br.com.diego.controle.Cliente"/>
<mapping class="br.com.diego.controle.PF"/>
<mapping class="br.com.diego.controle.PJ"/>
<mapping class="br.com.diego.controle.DocReceita"/>
<mapping class="br.com.diego.controle.CPF"/>
<mapping class="br.com.diego.controle.CNPJ"/>
<mapping class="br.com.diego.controle.Endereco"/>
<mapping class="br.com.diego.controle.Pet"/>
<mapping class="br.com.diego.controle.Cachorro"/>
<mapping class="br.com.diego.controle.Gato"/>
<mapping class="br.com.diego.controle.Servico"/>
<mapping class="br.com.diego.controle.Banho"/>
<mapping class="br.com.diego.controle.Consulta"/>
<mapping class="br.com.diego.controle.Telefone"/>
<mapping class="br.com.diego.controle.Tosa"/>
<mapping class="br.com.diego.controle.Vacina"/>
</session-factory>
</hibernate-configuration>

HeidiSQL

  • Did you try running the query directly on Mysql to see if it really thinks the record? I would run this on mysql: select cliente0_.idCliente as idClient2_2_, cliente0_.email as email3_2_, cliente0_.nome as nome4_2_, cliente0_.senha as senha5_2_, cliente0_.tipo as tipo1_2_ from Cliente cliente0_ left outer join PF cliente0_1_ on cliente0_.idCliente=cliente0_1_.idCliente left outer join PJ cliente0_2_ on cliente0_.idCliente=cliente0_2_.idCliente where cliente0_.email='[email protected]' and cliente0_.senha='root'

  • Post your persistence.xml, I have a slight suspicion that I know where the error is occurring.

  • do not possess persistence.xml only Hibernate.cfg.xml

2 answers

2

There is no mistake.

The Hibernate message is because it is showing the query being executed, since you have set it up like this through the show_sql.

"Error in authentication" is your own message and means that the database query did not return any record.

First, make sure you have no other relevant message in the log.

Second, check if you really have the record with the values corresponding to the email and password in the database.

Third, make sure that Java is running the latest version of your code. Rebuild classes, remove temporary files, etc.

  • Thank you so much for the answer, that was exactly what I hoped not to see errors too and according to the photo I put of the program Heidisql the values are being recorded in the Mysql database, I still do not solve the problem friend.

  • Could you have any more suggestions?

  • @diego Another idea is that your persist method is being called after authentication, so at that point there will be nothing in the database.

  • I was advised to change the Try block for before the block to generate tables and consequently the method persists now this being called before the authentication even so I continue with the same problem.

  • @diego is not before the block generate tables. You need to maintain a coherent order. First it generates tables, then it inserts the data and then it accesses them. Anyway, this shouldn’t be a problem unless you’re cleaning the bank every time you run the program. Other problems with your code is that you don’t use transaction to enter into the database, but use transaction to read the data. Also, it’s hard to say what might be happening without having the full log. Did you ever run the Hibernate query to see if it works? It may also be permission problem.

1

public Autenticavel autenticar(String usuario, String senha) is returning an interface, tries to change to public Cliente autenticar(String usuario, String senha)

  • I switched Authenticatable.java to: package br.com.diego.controle;&#xA;&#xA;public interface Autenticavel {&#xA;&#xA; public Cliente autenticar(String usuario, String senha);&#xA;&#xA; public boolean existe(String usuario);&#xA;} in Client.java changed @Override&#xA; public Cliente autenticar(String usuario, String senha){&#xA; return (Cliente) ClienteMTD.autenticar(usuario, senha);&#xA; } and in Clientemtd.java changed: public static Cliente autenticar(String usuario, String senha) the error still remains the same

  • I don’t understand why this happens where cliente0_.email=? and cliente0_.senha=? will be a problem in the way I wrote it GerarTabelas();&#xA; if (autenticar("[email protected]", "root") != null) {&#xA; System.out.println("Usuário autenticado");&#xA; } else {&#xA; System.out.println("Erro na autenticação");&#xA; } in Testandohibernate.java?

  • Put the Try block before generating tables and see if solved, not posted the whole persisting method here right? has the save or merge method in it to persist?

  • I posted the whole persisting method now, take a look. I tried to put the Try block before and still continue with Error in authentication.

  • Save method in Clientemtd class.java: public class ClienteMTD {&#xA; &#xA; public static boolean salvar(Cliente p) {&#xA; Session session;&#xA; session = HibernateUtil.getInstance();&#xA; Transaction tx = null;&#xA; try {&#xA; tx = session.beginTransaction();&#xA; session.save(p);&#xA; tx.commit();&#xA; return true;&#xA; } catch (Exception e) {&#xA; tx.rollback();&#xA; e.printStackTrace();&#xA; return false;&#xA; } finally {&#xA; session.close();&#xA; }&#xA; }

  • Ok, then continue with the Try block before Gerard tables and try to change q.list() to q.getResultList()

  • In the authenticate method? I tried switching to q.getResultList() and got the error message: cannot find symbol symbol: method getResultList() location: variable of type Query, I’m not sure I understand you at all.

Show 2 more comments

Browser other questions tagged

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