Pass jTextField value to Namedquery

Asked

Viewed 36 times

1

I have some jTextfFields where I need to send to the DAO their values, these values are arriving correctly in the DAO, but the return of NameQuery is being null. There is no mistake, only the return is null, consequently does not write to the bank.

What is strange ( for me) ,is that after a lot of trying, I decided to test and found that if I set the values so that they already start filled in jTextField, the return of DAO is not null, and yes the due return.

In the case below the "number" is the String that came from jTextField and was sent to DAO, and null is the return of NamedQuery.(made a sout)

numero recebido:  5555
dao: null

In this case, I manually set to start the jTextField completed. The return is correct and writes to the bank.

numero recebido:  5555
dao: 5555

Below is what I thought it was important to add so that someone can help with the question of why this behavior and help correct errors that might be causing it, or even other errors. Thank you

Entidade Car

@Entity
@DynamicUpdate(value = true)
@NamedQueries({
    @NamedQuery(name = "Carro.findAll", query = "SELECT distinct c FROM Carro c"),
    @NamedQuery(name = "Carro.findByCarroId", query = "SELECT c FROM Carro c WHERE c.id = :id"),
    @NamedQuery(name = "Carro.findByCarroIdAndDescricao", query = "SELECT c FROM Carro c WHERE c.id = :id and c.numero = :numero"),
    @NamedQuery(name = "Carro.findByCarroNumero", query = "SELECT c FROM Carro c WHERE c.numero = :numero")})
public class Carro implements EntidadeBase, Serializable {

    private static final long serialVersionUID = 1L;
    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idCarro")
    private Integer id;
    @Column(name = "numeroCarro")
    private String numero;

Method in DAO to fetch the value of jTextField

 public Carro buscarPorNumero(String numero) {
        System.out.println("NUMERO RECEBIDO: " + numero);
        EntityManager em = getEm();
        Carro carro = null;
        try {
            carro = (Carro) em.createNamedQuery("Carro.findByCarroNumero")
                    .setParameter("numero", numero)
                    .getSingleResult();

        } catch (NoResultException | NonUniqueResultException nre) {
            JOptionPane.showMessageDialog(null, nre.getMessage());
        }
        System.out.println("DAO: " + carro);

        return carro;

    }

Method to save, in the view, I left only the code referring to specific issue to not pollute too much.

public void salvar() {
        CarroDao carroDao = new CarroDao();
        Locall locall = new Locall();
        Envio envio = new Envio();

        List<Carro> carros = new ArrayList();
        List<String> lista = new ArrayList();

        if (jTextField1.getText().trim().equals("") == false) {
            lista.add(jTextField1.getText());
            System.out.println("PRIMEIRO:" + jTextField1.getText());
        }
        if (jTextField2.getText().trim().equals("") == false) {
            lista.add(jTextField2.getText());
            System.out.println("SEGUNDO:" + jTextField2.getText());
        }
        if (jTextField3.getText().trim().equals("") == false) {
            lista.add(jTextField3.getText());
            System.out.println("TERCEIRO:" + jTextField3.getText());
        }
        if (jTextField4.getText().trim().equals("") == false) {
            lista.add(jTextField4.getText());
            System.out.println("QUARTO:" + jTextField4.getText());
        }


        for (int i = 0; i < lista.size(); i++) {
            carros.add((Carro) carroDao.buscarPorNumero(lista.get(i)));
            System.out.println("Carro adicionado: " + lista.get(i));

        }
        envio.setCarros(carros);   

        try {
            EnvioDao ci = new EnvioDao();
            ci.save(envio);
            JOptionPane.showMessageDialog(null, "Gravado !");
            modelo.limpaLista();
            preencherTabela();
        } catch (Exception erro) {
            JOptionPane.showMessageDialog(null, "Erro na Gravação:" + erro);
        }
        refresh();
        clearSelection();

    }

update1

if (jTextField1.getText().trim().equals("") == false) {
        lista.add(jTextField1.getText().trim());
        System.out.println("PRIMEIRO:" + jTextField1.getText());
    }
  • 1

    By your code, you check the text of jTextField to see if it is not empty and then add it in a list to search for the cars referring to the texts (numbers). Check the following: 1 - no if you treat the text of jTextField with the function .trim() to remove spaces from the string, but when adding to the list you do not use the function (uses only the .getText()), this may be causing the behavior. 2 - In your if of the method salvar(), .equals() already returns a boolean then it is not necessary to compare with false, just put a ! in front of the sentence.

  • @Andre Gusmao thanks, I did what you suggested, and did not solve, I did one more test (I added the change in update 1) in the above question, and it worked, basically sent 'id’s' straight to dao' where there is a method that searches for 'id', and recorded correctly. Maybe the problem is in the 'Namedquery', or not? But even so, to get the 'id', I need to search by the ' number' in this case would be the 'Description''.

  • 1

    I think the Namedquery is correct. The problem is that when executing the method buscarPorNumero DAO method may be falling into one of the exceptions you stated: Noresult if you don’t have a car with that number or Nonuniqueresult in case you have more than one car with the number you are passing. Have you debugging this method to provide more details of what is happening?

  • @Andre Gusmao thanks again, I must have missed something about your first comment, because ( as update 1, I edited now) only adding the trim() by passing the String to the DAO solved. The jTextfield is getting an empty space before the String typed, hence the null return of DAO.

  • Glad you solved. I will post an answer to not leave the question pending ok?

  • No problem, thank you.

Show 1 more comment

1 answer

0


By your code, no if:

if (jTextField1.getText().trim().equals("") == false)

You handle the text of jTextField with the function. Trim() to remove spaces from the String, but when adding to the list you do not use the function (use only .gettext()), this may be causing the behavior since the value passed to the DAO may contain spaces.

To resolve do:

//O .equals já retorna um booleano
if (!jTextField1.getText().trim().equals("")) {
    //adicione o texto do jTextField tratado com o .trim()
    lista.add(jTextField1.getText().trim());
}

Browser other questions tagged

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