I read somewhere that when a session is cleared or a transaction is completed, the session itself is closed by Hibernate.
A flush does not close a session. However, starting with Hibernate 3.1, a commit will close the session if you set current_session_context_class to " thread " or " jta ", or if you use TransactionManagerLookup (required JTA) and getCurrentSession() .
The following code illustrates this (here current_session_context_class set to thead ):
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 threa d and section 2.5. Context sessions in the background documentation on this.
So, how can I reuse a Hibernate session in the same thread that was previously closed?
Use the built-in managed strategy (set the current_session_context_class property to managed ) or use the custom CurrentSessionContext obtained from ThreadLocalSessionContext and override ThreadLocalSessionContet.isAutoCloseEnabled() .
Let's look at the links above again, as well as What about an extended session template for long conversations?
source share