SQL/ JPQL query

Asked

Viewed 201 times

0

Friends, good afternoon.

I have a table in the database called Question Inside the table I have two columns that are code (id) and question. I have a filter that I can not specifically bring only code and ask because the return of the method is an object. I can only return the entire object.

How do I return only the code and the question table question?

It’s like I’m gonna make a:

select codigo, pergunta from Questao where curso_codigo = ?1 and complexidade = ?2; 

Can someone help me?

Follows the method:

@SuppressWarnings("unchecked")
    public List<Questao> geraSimuladoPorFiltro(Long codigoCurso,
            Integer complexidade, Integer numeroDeQuestoes) {
        String query = "from Questao WHERE curso_codigo = ?1 AND complexidade = ?2";
                List<Questao> questoes = manager.createQuery(query)
                .setParameter(1, codigoCurso)
                .setParameter(2, complexidade)
                .setMaxResults(numeroDeQuestoes)
                .getResultList();
        for (Questao questao : questoes) {
            System.out.println(questao.getCodigo());
            System.out.println(questao.getPergunta());
        }
        return questoes;
    }
  • Cara retrieves the entire object then iterates and removes only the code and asks it... You generated toString(); in the Questao class?

  • I think that this is not a good alternative, both in terms of processing and memory consumption, there is no need to load more data than it will need the database, up to why, the entity Questao can be great.

1 answer

2


You can directly return one Map, just write the following query:

SELECT new Map(q.codigo, q.pergunta) FROM Questao q WHERE q.curso_codigo = ?1 AND q.complexidade = ?2 This query should return a Map object whose key will be the code and the value is Question.
  • Thank you friend, it was perfectly settled.

Browser other questions tagged

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