Problema para popular tabela de Relacionamento Hibernate 3 com atributo

1 resposta
V

Bom dia,

Não sei se estou dando mole em algum detalhe mas, eu tenho duas tabelas Projeto e tarefa é um relacionamento N - M e a tabela de relacionamento é projetotarefa com os atributos idconsultor, datacriação e status da tarefa no projeto

porém oque esta acontecendo é que quando eu vou gerar as tarefas desse projeto o hibernate só grava um registro na tabela de relacionamento mas sempre eu gravo mais de uma tarefa para um projeto…

segue abaixo meu mapeamento
ActionGeraTarefas.java

public class ActionTelaGerarTarefas extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String comando;
	private Projeto p;
	private Demandante d;
	private List<Tarefa> tarefas;

	@Override
	public String execute() throws Exception {
		
		GenericDaoHibernateImpl<Projeto, Integer> daoProjeto = new GenericDaoHibernateImpl<Projeto, Integer>(Projeto.class);
		GenericDaoHibernateImpl<Demandante, String> daoDemandante = new GenericDaoHibernateImpl<Demandante, String>(Demandante.class);
		
		if (comando.equals("Gerar Tarefas")) {

			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction transaction = session.getTransaction();
			try {
				transaction.begin();
				p = daoProjeto.findById(p.getId());
				p.setStatus(StatusProjeto.EMANDAMENTO);
				d = daoDemandante.findById(d.getCpf());
				p.setDemandante(d);
				p.setTarefas(tarefas);
				
				ProjetoTarefaId pti = new ProjetoTarefaId();
				ProjetoTarefa pt = new ProjetoTarefa();
				for (Tarefa t : tarefas) {
					pti.setProjeto(p);
					pti.setTarefa(t);
					pt.setChaveComposta(pti);
					pt.setDataCriacao(new Date(10000000000L));
					pt.setStatus(StatusTarefa.CADASTRADA);
					session.save(pt);
				}
				daoProjeto.update(p);
				transaction.commit();
				StatusProjeto.EMANDAMENTO.enviarEmail("Report Status : Em Andamento");
			
				addActionMessage("Projeto alocado com o demandante " + p.getDemandante().getNome() + "e tarefas Geradas para o projeto " + p.getId()+" geradas com successo");
			} catch (Exception e) {
				transaction.rollback();
				e.printStackTrace();
				e.getMessage();
				addActionMessage("Ocorreu um erro : " + e.getMessage() + e.getCause());
				return ActionSupport.INPUT;
			}
		}
		return ActionSupport.INPUT;
		
	}

ProjetoTarefa.java

public class ProjetoTarefa implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1200780585149359893L;
	private ProjetoTarefaId chaveComposta;
	private StatusTarefa status;
	private Date dataCriacao;

        get's e set's

ProjetoTarefaId.java

public class ProjetoTarefaId implements Serializable{

	private static final long serialVersionUID = -6109601058703193837L;
	private Projeto projeto;
	private Tarefa tarefa;
	
        gets e sets
ProjetoTarefa.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
	
	<hibernate-mapping package="modelo">
		
		<typedef name="enum" class="util.EnumUserType">
			<param name="classeEnum">enums.StatusTarefa</param>
		</typedef>
		
		<class name="modelo.ProjetoTarefa" table="projetotarefa">
															 
			<composite-id name="chaveComposta" class="modelo.ProjetoTarefaId" >
				
				<key-many-to-one name="projeto" 
								 column="idprojeto" 
								 class="modelo.Projeto" />
				
				<key-many-to-one name="tarefa" 
								 column="idtarefa" 
								 class="modelo.Tarefa" />
			</composite-id>
			
			<property name="status" column="status" type="enum" />
			<property name="dataCriacao" column="data" type="date" />
			
		</class>
	</hibernate-mapping>

Agradeço a atenção dispensada

1 Resposta

V

Consegui solucionar, como forma de contribuição a comunidade vou postar a resposta para ajudar a outras pessoas que possam ter duvidas.

O erro tava no loop for, para cada iteração do for eu tenho que abri e fechar transação, para o update no projeto eu não preciso pois o meu dao ja tem begin e commit

public class ActionTelaGerarTarefas extends ActionSupport{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String comando;
	private Projeto p;
	private Demandante d;
	private List<Tarefa> tarefas;

	@Override
	public String execute() throws Exception {
		
		GenericDaoHibernateImpl<Projeto, Integer> daoProjeto = new GenericDaoHibernateImpl<Projeto, Integer>(Projeto.class);
		GenericDaoHibernateImpl<Demandante, String> daoDemandante = new GenericDaoHibernateImpl<Demandante, String>(Demandante.class);
		
		if (comando.equals("Gerar Tarefas")) {

			Session session = HibernateUtil.getSessionFactory().openSession();
			Transaction transaction = session.getTransaction();
			try {
				
				p = daoProjeto.findById(p.getId());
				p.setStatus(StatusProjeto.EMANDAMENTO);
				d = daoDemandante.findById(d.getCpf());
				p.setDemandante(d);
				p.setTarefas(tarefas);
				
				ProjetoTarefaId pti = new ProjetoTarefaId();
				ProjetoTarefa pt = new ProjetoTarefa();
				
				
				//o erro era esse, para cada iteração do for eu tenho que abrir uma transação e dar commit
				for (Tarefa t : tarefas) {
					transaction.begin();   
					pti.setProjeto(p);
					pti.setTarefa(t);
					pt.setChaveComposta(pti);
					pt.setDataCriacao(new Date(10000000000L));
					pt.setStatus(StatusTarefa.CADASTRADA);
					session.save(pt);
					transaction.commit();
				}
				
				daoProjeto.update(p);
				
				StatusProjeto.EMANDAMENTO.enviarEmail("Report Status : Em Andamento");
			
				addActionMessage("Projeto alocado com o demandante " + p.getDemandante().getNome() + "e tarefas Geradas para o projeto " + p.getId()+" geradas com successo");
			} catch (Exception e) {
				transaction.rollback();
				e.printStackTrace();
				e.getMessage();
				addActionMessage("Ocorreu um erro : " + e.getMessage() + e.getCause());
				return ActionSupport.INPUT;
			}
		}
		return ActionSupport.INPUT;
		
	}
Criado 20 de abril de 2010
Ultima resposta 21 de abr. de 2010
Respostas 1
Participantes 1