开发者

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 ca开发者_如何学Pythonn 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜