Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse Hibernate session in thread

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

like image 542
Mark Avatar asked Dec 09 '22 16:12

Mark


2 Answers

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?

like image 194
Pascal Thivent Avatar answered Dec 24 '22 21:12

Pascal Thivent


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.

like image 33
Daniel Avatar answered Dec 24 '22 22:12

Daniel