doubt about JPQL

0

Hello everyone. I am using JPQL in my project to create some database access commands and I am having difficulty manipulating the language. I'm posting the snippet of code I'm having trouble with.

public Usuario porNome(String nome) {
    Usuario usuario = null;
    try {
        usuario = this.manager.createQuery(" from Usuario where lower(nome) = :nome", Usuario.class)
                .setParameter("nome",nome.toLowerCase()).getSingleResult();
    } catch (NoResultException e) {
        // Nenhum usuario encontrado com o nome informado.
    }
    return usuario;
}

In this method, I'm getting a parameter called "name" and I'm looking in the "User" table to see if I can find any record with that name. I am using this method for a search field to query users from my system.

The problem is that with this code I posted above, it returns only records that have exactly the same name that I type in the search field, including uppercase and lowercase. For example, if there is a record in my bank named "BRUNO DE TAL", I need to type "BRUNO DE TAL" in the search field in order for my search to find this record. If I type only "BRUNO" or "bruno de tal", it does not find the record. What I want to know is how I should rewrite my JPQL code above and make it:

  • Ignore the question of uppercase and lowercase. For example, if there is a record named "Bruno" in the database, I want it to be found both when I type "Bruno" and when I type "bruno" in the search field.

  • Find bank records by entering only part of the name. For example, if there is a database record named "Bruno de tal", I want this record to be found when I type "Bruno" or "de" or "tal" in the search field.

    li>

I am a beginner in JPQL and still confuse some commands with SQL. So I would like to ask for your knowledge.

Thank you all for posting any response or suggestion.

    
asked by anonymous 21.10.2016 / 04:56

1 answer

-1

You can solve your need by using the LIKE command, which also exists in JPQL.

And to solve the mai / min problem, just use the lower function on both sides.

... where lower (name) LIKE lower (: name) ...

And at the time of setting the name:

"%" + name + "%"

However, there is a possible implementation problem. If for some reason, there is more than one person with the same "chunk of name", the singleresult function will return an exception because it will find more than one record. In this case, you should return a list.

    
21.10.2016 / 12:29