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
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With