How to insert a String variable into a hql?

0

I need to make a query in the database and return only the values based on the variable, my code returns the list with all the data of the city field, I want to return only the cities based on the state that the user select first. The state return (the variable that has to be inserted into the hlq) would be 'sgEstado'

public List<FilialComplementoTO> findCidadesByDsCidade() throws IntegrationException {
        List cidades;
          List<FilialComplementoTO> listOk ;
        try {
              Session session = InitSessionFactory.getInstance().getCurrentSession();
                StringBuffer hql = new StringBuffer();
                hql.append(" select g.dsCidade from FilialComplementoTO g ");
                hql.append(" group by g.dsCidade ");
                Query objQuery = session.createQuery(hql.toString());

                cidades = (List) objQuery.list();
                 listOk = new ArrayList<FilialComplementoTO>();
                for(Object obj: cidades){
                    FilialComplementoTO comple = new FilialComplementoTO();
                    comple.setDsCidade(obj.toString());
                    listOk.add(comple);
                }
                System.out.println(cidades);
        } catch (Exception e) {
            Logger.getLogger(this.getClass().getName()).error(e.getMessage());
            throw new IntegrationException(e);
        }
        return listOk;
    }
    
asked by anonymous 22.10.2014 / 13:29

1 answer

2

Use parameters. Example

StringBuffer hql = new StringBuffer();
hql.append(" select g.dsCidade from FilialComplementoTO g ");

// filtro utilizando parâmetro:
hql.append(" where g.sgEstado = :estado");
hql.append(" group by g.dsCidade ");
Query objQuery = session.createQuery(hql.toString());

// setando o valor do parâmetro:
objQuery.setParameter("estado", sgEstado)

If your ORM (Hibernate, Eclipse, OpenJPA, ...) does not support named parameter, you might have to do this:

...
hql.append(" where g.sgEstado = ?");
...
objQuery.setParameter(0, variavelStringContendoEstado)

I still remember a version (which I can not remember) of an ORM (which I can not remember which) where the parameters were indexed in 1. In this case, to set the first parameter of the query:

objQuery.setParameter(1, variavelStringContendoEstado)

For more details, see: Oracle Documenation - Java Persistence API - Chapter 10 JPA Query

    
22.10.2014 / 16:35