Erro hibernate. sessao fechada

9 respostas
R

Tenho um método que preciso obter uma coleção macada como lazy.
Como o objeto foi obtido através de outra sessao que já está fechada, crio uma nova sessao, torno o objeto persistente através do lock e então chamo o método cliente.getOrcamentos(). Até ai vai bem. Após isso, a sessao é fechada e então o erro abaixo é gerado. Caso eu nao feche a sessao o erro nao é gerado.
No momento, o getOrcamentos devolve um List vazio, pois ainda não tem nenhum orcamento.
O estranho é o fato do erro ser gerado depois. Alguém sabe o que pode estar acontecendo?

public void actionPerformed(ActionEvent e){
				cliente = LocalizadorObjetos.obterCliente();
				if (cliente !=null){
					Session session = HibernateUtil.getSession();
					session.lock(cliente,LockMode.NONE);
					visaoPesquisaOrcamento.setCampoNome(cliente.getNome());
					visaoPesquisaOrcamento.setLinhas( cliente.getOrcamentos() );
					session.close();
				}

			}

Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@1e3118a [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@f4f44a [ acquireIncrement -> 1, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, idleConnectionTestPeriod -> 3000, initialPoolSize -> 5, maxIdleTime -> 300, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@1315d34 [ description -> null, driverClass -> null, factoryClassLocation -> null, jdbcUrl -> jdbc:firebirdsql://servidor:3050/c:\SOR\BANCO.FDB, properties -> {user=******, password=******, lc_ctype=WIN1252} ] , preferredTestQuery -> null, propertyCycle -> 300, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, usesTraditionalReflectiveProxies -> false ] , factoryClassLocation -> null, numHelperThreads -> 3, poolOwnerIdentityToken -> 1e3118a ]
15:43:24,351Hibernate: select this_.CLIENTE_ID as CLIENTE1_0_, this_.VERSAO as VERSAO0_0_, this_.nome as nome0_0_ from CLIENTE this_ where lower(this_.nome) like ? order by this_.nome asc
15:43:29,769org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: src.model.Cliente.orcamentos - no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:191)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:183)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:48)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:218)
at src.swing.model.TableModelPadrao.getRowCount(TableModelPadrao.java:21)
at javax.swing.JTable.getRowCount(JTable.java:1797)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1428)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:740)
at javax.swing.JComponent.paint(JComponent.java:1003)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4930)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4883)
at javax.swing.JComponent._paintImmediately(JComponent.java:4826)
at javax.swing.JComponent.paintImmediately(JComponent.java:4633)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:451)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:114)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-0" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: src.model.Cliente.orcamentos - no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:191)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:183)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:48)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:218)
at src.swing.model.TableModelPadrao.getRowCount(TableModelPadrao.java:21)
at javax.swing.JTable.getRowCount(JTable.java:1797)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1428)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:740)
at javax.swing.JComponent.paint(JComponent.java:1003)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4930)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4883)
at javax.swing.JComponent._paintImmediately(JComponent.java:4826)
at javax.swing.JComponent.paintImmediately(JComponent.java:4633)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:451)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:114)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
15:43:32,122org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: src.model.Cliente.orcamentos - no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:191)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:183)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:48)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:218)
at src.swing.model.TableModelPadrao.getRowCount(TableModelPadrao.java:21)
at javax.swing.JTable.getRowCount(JTable.java:1797)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1428)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:740)
at javax.swing.JComponent.paint(JComponent.java:1003)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4930)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4883)
at javax.swing.JComponent._paintImmediately(JComponent.java:4826)
at javax.swing.JComponent.paintImmediately(JComponent.java:4633)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:451)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:114)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
Exception in thread "AWT-EventQueue-0" org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: src.model.Cliente.orcamentos - no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:191)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:183)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:48)
at org.hibernate.collection.PersistentBag.size(PersistentBag.java:218)
at src.swing.model.TableModelPadrao.getRowCount(TableModelPadrao.java:21)
at javax.swing.JTable.getRowCount(JTable.java:1797)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1428)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
at javax.swing.JComponent.paintComponent(JComponent.java:740)
at javax.swing.JComponent.paint(JComponent.java:1003)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:559)
at javax.swing.JComponent.paintChildren(JComponent.java:840)
at javax.swing.JComponent.paint(JComponent.java:1012)
at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4930)
at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4883)
at javax.swing.JComponent._paintImmediately(JComponent.java:4826)
at javax.swing.JComponent.paintImmediately(JComponent.java:4633)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:451)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:114)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

9 Respostas

_fs

Tenta flush() antes de close()

R

Deu o mesmo erro.
O erro é dado após a execução do método. E não no momento do close.

_fs

Mnham, aqui:

LocalizadorObjetos.obterCliente();
Abre a sessão e pega o cliente? Depois fecha a sessão que pegou o cliente?

R

Isso. Esse método carrega a tela de pesquisa de clientes, abre a sessao, apresenta os clientes, pega o que o usuário selecionou e fecha a sessao.

O erro está acontecendo depois do método inteiro ser executado. Não após o session.close(). Já coloquei alguns comandos após o session.close() e o erro só era gerado após sair do método.

_fs

Então acontece isso aqui:

sessao1 = pegaSessao();
cliente = sessao1.get( Cliente.class, 1 );
fechaSessao( sessao1 );

sessao2 = pegaSessao();
cliente.getRelacionamentoLazy();

Ferrou né cara :smiley:

O proxy Cliente que deveria carregar a coleção do relacionamento está associado a uma sessão fechada.

Duas soluções:

  1. Carregue a coleção do relacionamento antes de fechar a primeira sessão
  2. Faça tudo numa sessão só
R

O pior é que não. Eu associo ele a nova sessao. Veja: session.lock(cliente,LockMode.NONE);
E mesmo assim, ele consegue fazer o cliente.getOrcamentos.
O erro é depois que termina o método actionPerformed().

R

Resolvi o problema, utilizando Hibernate.initialize.
Achei estranho, pois achei que o fato de fazer o getOrcamentos, já iria inicializar, trazer os objetos lazy.
Alguém sabe explicar melhor isso?

cliente = LocalizadorObjetos.obterCliente(); if (cliente!=null){ Session session = HibernateUtil.getSession(); session.lock(cliente,LockMode.NONE); Hibernate.initialize(cliente.getOrcamentos()); session.close(); visaoPesquisaOrcamento.setCampoNome(cliente.getNome()); visaoPesquisaOrcamento.setLinhas( cliente.getOrcamentos() ); }

_fs

Você já estava fechando a sessão antes de getOrcamentos() como esse código agora ou não?

E sim, ao fazer getOrcamentos() a coleção deveria ser inicializada.

R

Não, antes eu só estava fechando depois de fazer o get. Mas o mais estranho é que o erro só era gerado depois do evento ActionPerformed ser executado.

Criado 1 de junho de 2005
Ultima resposta 2 de jun. de 2005
Respostas 9
Participantes 2