how does hibernate sessionfactory manage session?

。_饼干妹妹 提交于 2019-12-05 00:49:19

问题


I have just got the relationship between Hibernate Session and Connection. But now, I get another question: how does hibernate sessionfactory manage session? In the following code segment: save() method of a DAO class:

Session session = sessionFactory.openSession();
   Transaction tx=null;
   tx=session.beginTransaction(); 
   session.save(transientInstance);
   session.flush();
   tx.commit();

When we call sessionFactory.openSession() , it will create a new session attached to the current thread (through the ThreadLocal), this session is also attached to a JDBC connection, But, as you can see, we don't need to close the session (session.close()), neither the connection. So, what is the lifecycle of a Hibernate session, in what circumstances it will be closed? automatically?


回答1:


I recommend the getCurrentSession method because only with this method you have the possibility to be sure that the session will be closed from hibernate

Configuration J2EE Current Session.

If you use the openSession method, you must close the sessions by yourself. After i begin to work with hibernate i thought it does'n matter which method I use because all session will be closed automatically... i was wrong. I had discovered with the SessionStatistics from hibernate SessionStatistics that the open session was already opened and never closed.

After i changed all calls to getCurrentSession and impl. the Session-per-request pattern opened session will be closed after work.

Transactions Basics.



来源:https://stackoverflow.com/questions/15613540/how-does-hibernate-sessionfactory-manage-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!