ID by variable it returns null and if you put the ID "in hand" it returns the right object

Asked

Viewed 54 times

0

I am trying to recover a code received by a request to recover objects from the database, but am encountering some problems.

Performing tests, replace the id coming from the request, by a forced value ("written in the hand") and managed to obtain the object.

Follows my code:

List<String> codigos = new ArrayList<>();


String idPeca = request.getParameter("idPeca");
ControlePeca cp = new ControlePeca();
for (Peca p1 : cp.buscarPecas(Peca.class)) {
    codigos.add(p1.getIdPeca());
}

for (String id : codigos) {
    System.out.println(id); //sai o id que, é o mesmo contigo em idPeca
    System.out.println(cp.buscarPorId(id)); //traz o objeto que tem o id
    System.out.println(cp.buscarPorId(idPeca)); //traz null
}


    Query query = session.createQuery(hql);
    query.setMaxResults(1);
    Peca peca = (Peca) query.uniqueResult();
    session.clear();
    session.close();
    return peca;
}

I have a class Pecadao that is called by the controller Controlepeca()

This is the method I tested by forcing the data. If I replace the id with a string in the database it returns correct, but not the variable.

public Peca buscarPorId(String id) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    String hql = "from peca p where p.id = '" + **id** + "' "; 
}

I would like to know why this search returns null just by coming from request.getParameter Obs: I have already checked if the value coming from the request has in the bank, and yes it has;

  • Face the first thing to do is to see if the value of Request is coming correctly. Since when you set this value manually the method can perform the search probably this value coming from the request is null or wrong. Try using request.getParameter("idPeca"). Trim(); Sometimes the parameter is coming with space and so the method is unable to find.

  • I got it, thanks, sorry for the delay :)

No answers

Browser other questions tagged

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