How to insert a String variable into an hql?

Asked

Viewed 485 times

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 selected before. The return of the status (the variable that has to be inserted in hlq) would be 'sgEstad'

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;
    }

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 may have to do so:

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

I still remember a version (I can’t remember which one) of a ORM (I can’t remember which one) 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

  • jdbc itself uses the index starting with 1. +1 in response.

Browser other questions tagged

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