Close in transaction with hibernate

1

Hello,

I need some help. I am trying to perform a transaction in hibernate.

The problem is that when giving a close, the data is modified in the database, but this warning occurs

  

WARN [CommonAnnotationBeanPostProcessor] Invocation of destroy method   failed on bean with name 'sessionCreator':   org.hibernate.SessionException: Session was already closed

The code I'm using is this:

Transaction transacao = null;
    try {
        transacao = session.beginTransaction();
        contaDao.atualiza(conta);
        transacao.commit();
        session.close();    
    } catch (Exception err) {  
        if (transacao != null) {
            transacao.rollback();
        }
    }

How can I resolve this problem?

Follow the whole method

 public void atualizarSaldo(LancamentoDados dados, double novoSaldo) {
    ContaBancaria conta = new ContaBancaria();
    HistoricoConta historicoSaldoConta = new HistoricoConta(this.historicoConta);
    conta.setCodContaBancaria(dados.getConta().getCodContaBancaria());
    conta.setNumeroContaBancaria(dados.getConta().getNumeroContaBancaria());
    conta.setSaldoContaBancaria(novoSaldo);
    conta.setAnotacaoContaBancaria("Sem conta");
    Transaction transacao = null;
    try {
        transacao = session.beginTransaction();
        System.out.println("Estou no try em atualiza");
        contaDao.atualiza(conta);
        historicoSaldoConta.inserirSaldoConta(conta);
        transacao.commit();
    } catch (Exception err) {
        System.out.println("Erro meu : " + err);
        if (transacao != null) {
            transacao.rollback();
        }
    }
}
    
asked by anonymous 07.06.2016 / 20:25

3 answers

0

In Excession says that your Session is already closed: Session was already closed I recommend doing a validation before closing the Session: To prevent it from attempting to close a Session already closed

if (this.session.isOpen()) {
      session.close();

    }
    
07.06.2016 / 21:06
0

You have already finished the session, ideally you should check to see if the session was opened and one to check if it is closed ... you put the 2 if, you can control what happens in the transactions of your code .

if(session.Open())
{
}
if(session.Close())
{}
    
07.06.2016 / 22:16
0

Personal get through this code:

Transaction transacao = null;
    Session sess = Sessao.getSessao();      
    try {
        transacao = sess.beginTransaction();
        contaDao.atualiza(conta);
        transacao.commit();
    } catch (Exception err) {
        System.out.println("Erro meu : " + err);
        if (transacao != null) {
            transacao.rollback();
        }
    } finally {          
        sess.close();              
    }
    
09.06.2016 / 20:44