java.lang.String can not be cast to com.sisEnade.tcc.modelo.Questao

1

Good afternoon. I'm having the following error:

java.lang.String can not be cast to com.sisEnade.tcc.modelo.Questao

However, I could not resolve the error. The purpose of the implementation is to create a filter, to bring to the user questions that are already registered in the database.

Can anyone help me? Here is the related code:

package com.sisEnade.tcc.dao;

import java.io.Serializable;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import com.sisEnade.tcc.modelo.Curso;
import com.sisEnade.tcc.modelo.Questao;

public class SimuladoFiltroDAO implements Serializable {

    private static final long serialVersionUID = 1L;

    @Inject
    private EntityManager manager;

    public Questao geraSimuladoPorFiltro(Curso curso, Integer complexidade) {
        return (Questao) manager
                .createQuery(
                    "select pergunta from Questao WHERE curso_codigo = ?1 AND complexidade = ?2")
                .setParameter(1, curso)
                .setParameter(2, complexidade)
                .getSingleResult();
    }

}

JSF page:

<h:panelGrid columns="2">

            <p:outputLabel value="Curso" for="curso" style="font-weight:bold" />
            <p:selectOneMenu id="curso"
                value="#{gerarSimuladoBean.cursoSelecionado}"
                converter="cursoConverter" required="true"
                requiredMessage="Preencha o curso">
                <f:selectItem itemLabel="Selecione..." />
                <f:attribute name="collectionType" value="java.util.ArrayList" />
                <f:selectItems value="#{cadastroQuestaoBean.cursos}" var="curso"
                    itemLabel="#{curso.nome}" itemValue="#{curso}" />
            </p:selectOneMenu>
        </h:panelGrid>


        <h:panelGrid id="gridComplexidade" columns="2">
            <p:outputLabel value="Complexidade da Questão" for="complexidade"
                style="font-weight:bold" />
            <p:selectOneMenu id="complexidade"
                value="#{gerarSimuladoBean.complexidadeSelecionada}" required="true"
                requiredMessage="Por favor, preencha a complexidade.">
                <f:selectItem itemLabel="Selecione..." />
                <f:selectItem itemLabel="1" itemValue="1" />
                <f:selectItem itemLabel="2" itemValue="2" />
                <f:selectItem itemLabel="3" itemValue="3" />
                <f:selectItem itemLabel="4" itemValue="4" />
                <f:selectItem itemLabel="5" itemValue="5" />
            </p:selectOneMenu>
            <p:commandButton value="Gerar Simulado" action="#{gerarSimuladoBean.gerarSimulado}"
                icon="ui-icon-disk" iconPos="right" update="frmCadastro">
            </p:commandButton>
        </h:panelGrid>

Model Questao:

package com.sisEnade.tcc.modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

/**
 * 
 * @author Felipe Portela
 *
 */

@Entity
public class Questao {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    @JoinColumn(name = "PERGUNTA")
    private String pergunta;

    @JoinColumn(name = "RESPOSTA_PADRAO_ITEM")
    private String respostaPadraoPerguntaItem;

    @JoinColumn(name = "RESPOSTA_DISCURSIVA")
    private String respostaDiscursiva;

    @ManyToOne
    @JoinColumn(name = "CURSO")
    private Curso curso;

    @JoinColumn(name = "COMPLEXIDADE")
    private Integer complexidade;

    @JoinColumn(name= "IDENTIFICA_QUESTAO_SUBJETIVA")
    private Boolean identificaQuestao = Boolean.FALSE;

    @ManyToOne
    @JoinColumn(name = "STATUS_QUESTAO")
    private Situacao_Questao statusPergunta;

    public Long getCodigo() {
        return codigo;
    }
    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public String getPergunta() {
        return pergunta;
    }
    public void setPergunta(String pergunta) {
        this.pergunta = pergunta;
    }

    public String getRespostaPadraoPerguntaItem() {
        return respostaPadraoPerguntaItem;
    }
    public void setRespostaPadraoPerguntaItem(String respostaPadraoPerguntaItem) {
        this.respostaPadraoPerguntaItem = respostaPadraoPerguntaItem;
    }
    public String getRespostaDiscursiva() {
        return respostaDiscursiva;
    }
    public void setRespostaDiscursiva(String respostaDiscursiva) {
        this.respostaDiscursiva = respostaDiscursiva;
    }
    public Situacao_Questao getStatusPergunta() {
        return statusPergunta;
    }
    public void setStatusPergunta(Situacao_Questao statusPergunta) {
        this.statusPergunta = statusPergunta;
    }

    public Boolean getIdentificaQuestao() {
        return identificaQuestao;
    }
    public void setIdentificaQuestao(Boolean identificaQuestao) {
        this.identificaQuestao = identificaQuestao;
    }
    public Integer getComplexidade() {
        return complexidade;
    }
    public void setComplexidade(Integer complexidade) {
        this.complexidade = complexidade;
    }

    public Curso getCurso() {
        return curso;
    }
    public void setCurso(Curso curso) {
        this.curso = curso;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((codigo == null) ? 0 : codigo.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Questao other = (Questao) obj;
        if (codigo == null) {
            if (other.codigo != null)
                return false;
        } else if (!codigo.equals(other.codigo))
            return false;
        return true;
    }   
}
    
asked by anonymous 12.10.2015 / 19:08

2 answers

1
  

Good afternoon. I'm having the following error:
  java.lang.String can not be cast to com.sisEnade.tcc.modelo.Questao

Your problem is that you are really trying to transform a string into an object of type Questao .

Evaluating the query that is running, we can verify that you are returning only the field pergunta , which is a string :

select pergunta from Questao WHERE curso_codigo = ?1 AND complexidade = ?2

The problem happens when you get the query result, which is a string , and tries to transform it into an object of type Questao :

return (Questao) manager.createQuery...

If you really want to receive an object of type Questao as a return, change your query to:

select q from Questao q WHERE q.curso_codigo = ?1 AND q.complexidade = ?2

The following should also work:

from Questao q WHERE q.curso_codigo = ?1 AND q.complexidade = ?2
    
12.10.2015 / 20:03
0

Just complementing the answer from the buddy up there, soon after I discovered it is also possible to get only the single column that is a String by changing the return type to String.

The filter looks like this:

public List<String> geraSimuladoPorFiltro(Long codigoCurso,
            Integer complexidade, Integer numeroDeQuestoes) {
        String query = "select pergunta from Questao WHERE curso_codigo = ?1 AND complexidade = ?2";
        List<String> questoes = manager.createQuery(query, String.class)
                .setParameter(1, codigoCurso).setParameter(2, complexidade)
                .setMaxResults(numeroDeQuestoes).getResultList();
        for (String q : questoes) {
            System.out.println(q);
        }
        return questoes;
    }
    
13.10.2015 / 17:46