Problemas para receber dados do tipo múltipla escolha

1 resposta
nilopadilha

Bom dia pessoal estou com um problema para receber dados do tipo múltipla escolha, por exemplo, quero cadastrar um pergunta no banco de dados com suas prováveis alternativas dentre elas uma será a resposta correta.

criei uma classe Pergunta, onde tenho as seguintes variáveis, descrição, um Arraylist de alternativa.

Mas não consigo encontrar uma forma para inserir no banco de dados os dados para que depois ele me exiba algo do tipo múltipla escolha, segue abaixo o código do meu projeto para que vocês possam analisar melhor.

Classe pergunta:

package br.gera.dominio;

import java.io.Serializable;
import java.util.ArrayList;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "pergunta")
@Entity
public class Pergunta implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private long id;

	private String descricao;

	@SuppressWarnings("rawtypes")
	private ArrayList alternativa = new ArrayList();

	private String resposta;

	public Pergunta() {

	}

	@SuppressWarnings("rawtypes")
	public Pergunta(long id, String descr, ArrayList alterna, String resp) {
		this.id = id;
		this.descricao = descr;
		this.alternativa = alterna;
		this.resposta = resp;

	}
//getters end setters

classe bean

package br.gera.Mbean;

import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import javax.faces.model.ListDataModel;

import br.gera.Dao.PerguntaDao;
import br.gera.Dao.impl.PerguntaDaoImpl;
import br.gera.dominio.Pergunta;

@ManagedBean(name = "perguntaMBean")
@SessionScoped
public class PerguntaMBean {

	private Pergunta pergunta;
	private ListDataModel<Pergunta> perguntas;

	public ListDataModel<Pergunta> getListarPegunta() {
		List<Pergunta> lista = new PerguntaDaoImpl().buscarTodos();
		perguntas = new ListDataModel<Pergunta>(lista);
		return perguntas;
	}

	public Pergunta getPergunta() {
		if (pergunta == null)
			pergunta = new Pergunta();
		return pergunta;

	}

	public void setPergunta(Pergunta pergunta) {
		this.pergunta = pergunta;
	}

	public String prepararAddPergunta() {
		pergunta = new Pergunta();
		return "form";

	}

	public String prepararAterarPergunta() {

		pergunta = (Pergunta) (perguntas.getRowData());

		return "edita";

	}

	public String Excluir() {

		Pergunta perguntemp = (Pergunta) (perguntas.getRowData());
		PerguntaDao dao = new PerguntaDaoImpl();
		dao.remover(perguntemp);
		return "form";

	}

	public String Salvar() {
		PerguntaDao dao = new PerguntaDaoImpl();
		dao.salvar(pergunta);
		return "form";

	}

	public String Alterar() {
		try {
			PerguntaDaoImpl dao = new PerguntaDaoImpl();
			dao.Update(pergunta);

		} catch (Exception e) {
			// TODO: handle exception
		}

		return "edita";

	}

}

classe dao

package br.gera.Dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.gera.Dao.PerguntaDao;
import br.gera.dominio.Pergunta;
import br.gera.util.HibernateUtil;

public class PerguntaDaoImpl implements PerguntaDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see br.gera.Dao.PerguntaDao#buscarTodos()
	 */
	@SuppressWarnings("unchecked")
	public List<Pergunta> buscarTodos() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		List<Pergunta> lista = session.createQuery("from Pergunta").list();
		t.commit();
		return lista;

	}

	// @SuppressWarnings("unchecked")
	// public List<Pergunta> buscarPorId() {
	// Session session = HibernateUtil.getSessionFactory().openSession();
	// return (List<Pergunta>) session.load(Pergunta.class, session);
	//
	// }

	public void salvar(Pergunta pergunta) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		session.save(pergunta);
		t.commit();
		session.clear();
		session.close();

	}

	public void remover(Pergunta pergunta) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction t = session.beginTransaction();
		session.delete(pergunta);
		t.commit();

	}

	public void Update(Pergunta pergunta){
		
			Session session = HibernateUtil.getSessionFactory().openSession();
			
			Transaction t = session.beginTransaction();
		try{
			session.update(pergunta);	
			session.flush();			
			t.commit();
			
		} catch (Exception e) {
			t.rollback();
		}
		
		
		session.clear();
		

	}

}

form de cadastramento de perguntas.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets">


<h:form>
	
		
		Descrição: <h:inputText id="descricao"
		value="#{ perguntaMBean.pergunta.descricao }" />

	<br />
		Alternativa: <h:inputText id="alternativa"
		value="#{ perguntaMBean.pergunta.alternativa }" />
	<br />
		
		Resposta: <h:inputText id="resposta"
		value="#{ perguntaMBean.pergunta.resposta }" />

	<br />

	<h:inputHidden value="#{ perguntaMBean.pergunta.id }" />

	<h:commandButton value="Salvar" action="#{ perguntaMBean.Salvar() }" />
	<a href="lista.jsf">Listar</a>

</h:form>


</html>

1 Resposta

drsmachado

Para mim, Pergunta 1 : N Respostas e Respostas N : 1 RespostaCorreta, não?
Logo, você precisa ter uma outra entidade Resposta, com, ao menos, os atributos valor (que representa o valor da resposta, String) e correta (que representa se é a opção correta ou não, Boolean). Além disso, a entidade Pergunta pode ter um atributo Resposta, que indique a resposta correta.
Assim, ao carregar uma pergunta, você lista as suas respectivas alternativas (a lista de respostas). Para correção, basta verificar se a opção selecionada é igual ao atributo respostaCerta.

Criado 1 de junho de 2012
Ultima resposta 1 de jun. de 2012
Respostas 1
Participantes 2