views:

164

answers:

2

Hello,

I've read somewhere that when a session is flushed or a transaction is committed, the session itself is closed by Hibernate. So, how can i reuse an Hibernate Session, in the same thread, that has been previously closed?

Thanks

+1  A: 

Wrong. The session is stays open, just a new transaction begins. The main thing is that all objects currently attached to the session STAY attached, so if you don't clear the session you have a memory leak here.

Daniel
Not always true
Pascal Thivent
+5  A: 

I've read somewhere that when a session is flushed or a transaction is committed, the session itself is closed by Hibernate.

A flush does not close the session. However, starting from Hibernate 3.1, a commit will close the session if you configured current_session_context_class to "thread" or "jta", or if you are using a TransactionManagerLookup (mandatory JTA) and getCurrentSession().

The following code illustrates this (with current_session_context_class set to thead here):

Session session = factory.getCurrentSession();
Transaction tx = session.beginTransaction();

Product p = new Product();
session.persist(p);
session.flush();
System.out.println(session.isOpen()); // prints true

p.setName("foo");
session.merge(p);
tx.commit();
System.out.println(session.isOpen()); // prints false

See this thread and the section 2.5. Contextual sessions in the documentation for background on this.

So, how can i reuse an Hibernate Session, in the same thread, that has been previously closed?

Either use the built-in "managed" strategy (set the current_session_context_class property to managed) or use a custom CurrentSessionContext derived from ThreadLocalSessionContext and override ThreadLocalSessionContet.isAutoCloseEnabled().

Again, see the above links and also What about the extended Session pattern for long Conversations?

Pascal Thivent
+1 for enlightening me
Daniel