Mark
Mark

Reputation: 70040

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

Upvotes: 4

Views: 6593

Answers (2)

Pascal Thivent
Pascal Thivent

Reputation: 570635

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?

Upvotes: 12

Daniel
Daniel

Reputation: 28104

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.

Upvotes: 2

Related Questions