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

Asked

Viewed 112 times

1

good afternoon. I have the following error:

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

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

Can someone help me? Follows 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();
    }

}

Page JSF:

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

Modelo 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;
    }   
}
  • Generates toString() from your Questao class.

2 answers

1


good afternoon. I have the following error:
java.lang.String cannot be cast to com.sisEnade.tcc.modelo.Questao

Your problem is you’re really trying to turn one string on an object of the type Questao.

By evaluating the query being executed, we can verify that you are only returning 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 result of the query, which is a string, and tries to turn into an object of the type Questao:

return (Questao) manager.createQuery...

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

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

As follows it should also work:

from Questao q WHERE q.curso_codigo = ?1 AND q.complexidade = ?2
  • Buddy, it worked perfectly. I can bring the questions by asking a Foreach and giving a getPerguntas.

0

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

The filter was as follows:

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

Browser other questions tagged

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