[RESOLVIDO] Finalizar Transação no hibernat antes de gerar relatorio

3 respostas
J

Estou construindo uma função que Insere na tabela ‘movimento’ e depois atualiza a tabela ‘servico’ com o idmovimento…
O problema é qua logo após eu mando imprimir um relatório com os respectivos dados que acabou de gravar, mas acontece que os serviços ainda não estão comitados, então o relatório retorna sem os serviços do cliente.

Utilizo um filtro para iniciar uma transação e finalizar no Hibernate…

@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            try {
                this.sf.getCurrentSession().beginTransaction();
                chain.doFilter(request, response);
                this.sf.getCurrentSession().getTransaction().commit();
                this.sf.getCurrentSession().close();
            } catch (Throwable ex) {
                try {
                    if (this.sf.getCurrentSession().getTransaction().isActive()) {
                        this.sf.getCurrentSession().getTransaction().rollback();
                    }
                } catch (Throwable t) {
                }
                throw new ServletException(ex);
            }
        } catch (Exception e) {
            this.sf.getCurrentSession().close();
            this.sf.getCurrentSession().beginTransaction();
            chain.doFilter(request, response);
            this.sf.getCurrentSession().getTransaction().commit();
            this.sf.getCurrentSession().close();
            //FacesContext.getCurrentInstance().getExternalContext().redirect("index.jsf");
        }
    }

Função com problema…

public void gerarMovimento(ActionEvent actionEvent) throws HibernateException, JRException, SQLException, IOException {
        MovimentoCTR movimentoCTR = new MovimentoCTR();
        Movimento movimento = new Movimento();
        movimento.setConta(conta);
        Date data = new Date(System.currentTimeMillis());
        movimento.setDatamovimento(data);
        movimento.setStatus("ABERTO");
        movimento.setValortotal(servCliente.getTotal());
        movimento.setDesconto(this.desconto);
        Integer id = movimentoCTR.inserir(movimento);

        movimento = movimentoCTR.carregar(id);

        ServicoCTR servicoCTR = new ServicoCTR();
        for (Servico s : servCliente.getListaServicos()) {
            s.setMovimento(movimento);
            servicoCTR.atulaizar(s);
        }
        this.desconto = 0.0;
        servicosClientes.remove(servCliente);

        Map parametros = new HashMap();

        parametros.put("idusuario", conta.getIdusuario());
        parametros.put("idcliente", servCliente.getCliente().getIdcliente());
        parametros.put("idmovimento", movimento.getIdmovimento());

        File file = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/relatorios/MovimentoCliente.jasper"));
        byte[] bytes = JasperRunManager.runReportToPdf(file.getPath(), parametros, getConnection());

        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        httpServletResponse.setContentType("application/pdf");
        httpServletResponse.setContentLength(bytes.length);

        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();

        servletOutputStream.write(bytes, 0, bytes.length);
        servletOutputStream.flush();
        servletOutputStream.close();
        FacesContext.getCurrentInstance().responseComplete();
    }

Precisava arrumar um jeito de terminar essa transação no banco de dados para gerar o relatório corretamente em seguida…
Desde já um muito obrigado.

3 Respostas

alexfe
Vc inicia o hibernate com uma classe dessa ?
import javax.faces.bean.ApplicationScoped;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.annotation.Scope;

@ApplicationScoped
@Scope("singleton")
public class HibernateUtil {

	private static SessionFactory sessionFactory = buildSessionFactory();

	/**
	 * Inicia a sessão de conexão com o banco
	 * @return SessionFactory
	 */
	private static SessionFactory buildSessionFactory() {
		try {
			if (sessionFactory == null) {
				sessionFactory = (new Configuration()).configure().buildSessionFactory();
			}
			return sessionFactory;
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new ExceptionInInitializerError("Erro ao criar conexăo SessionFactory");
		}
	}

	/**
	 * Inicia a sessão ou retorna a mesma
	 * @return
	 */
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null)
			buildSessionFactory();

		return sessionFactory;
	}
	
	/**
	 * Commit manual da transao corrente
	 */
	public static void commitTransaction(){
		getSessionFactory().getCurrentSession().beginTransaction().commit();
	}

}
A solução seria após vc inserir sei registro vc chama
HibernateUtil.commitTransaction();
J

Perfeito…funcionou certinho alexafe
Muito obrigado msm…

alexfe

Valeu parceiro, coloca o post como resolvido.

Criado 9 de novembro de 2014
Ultima resposta 11 de nov. de 2014
Respostas 3
Participantes 2