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?
The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.
A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.
Most importantly, the SessionFactory in Hibernate is responsible for the creation of Session objects. The Hibernate Session provides methods such as save, delete and update, all of which are used to perform CRUD-based operations on the database to which the SessionFactory connects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With