Ignore parameter if null

0

I have the following method that searches the database:

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 into the trap that it will not bring anything if the generation is null. How can I resolve to do for example: If the generation is null ignore?

    
asked by anonymous 05.01.2017 / 23:38

1 answer

3

Douglas, as I understood the problem, we recommend creating the logic to check if your form id generation is not null, mount the select and if necessary pass the parameter. In the case below if id is 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;
}
    
06.01.2017 / 04:31