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?
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.