Reusing a Hibernate Session in a Stream

I read somewhere that when a session is cleared or a transaction is completed, the session itself is closed by Hibernate. So, how can I reuse a Hibernate session in the same thread that was previously closed?

thanks

+4
source share
2 answers

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?

+11
source

Wrong. The session remains open, only a new transaction begins. The main thing is that all the objects that are currently connected to the STAY session are connected, so if you do not clear the session, you have a memory leak here.

+2
source

Source: https://habr.com/ru/post/1309186/


All Articles