Ignore parameter if null

Asked

Viewed 308 times

0

I have the following method that does a database search:

public Collection<Habilidade> pesquisar(HabilidadeForm form) throws Exception {
        String query = "select u from Habilidade u where u.nome like ?1 and u.geracao = ?2";
        Collection<Habilidade> resultado =
            em.createQuery(query).setParameter(1, "%" + form.getNome() + "%")
                .setParameter(2, form.getGeracao()).getResultList();

        return resultado.isEmpty() ? findAll() : resultado;
    }

If I do the same query in the database would be an example:

select * from habilidade where nome like '%Bl%' and geracao_id = null;

I have a problem where no generation is null, so I fall for the catch that it will not bring anything if generation is null. How can I choose to do for example: If the generation is null ignore ?

1 answer

3


Douglas, in the way I understood the problem, it is recommended to create the logic to check if your form to general is not null, mount select and if necessary pass parameter. In the case below if the geracao_id for null, select will only consider the name.

public Collection<Habilidade> pesquisar(HabilidadeForm form) throws Exception {
    String query = "select u from Habilidade u where u.nome like ?1";

    if (form.getGeracao() != null) {
       query +=  " and u.geracao = ?2";
    } 

    Query q = em.createQuery(query);
    q.setParameter(1, "%" + form.getNome() + "%");

    if (form.getGeracao() != null) {
        q.setParameter(2, form.getGeracao());
    }   

    Collection<Habilidade> resultado = q.getResultList();

    return resultado.isEmpty() ? findAll() : resultado;
}

Browser other questions tagged

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