How properly "lifecycle" of a Hibernate session under Spring should be done?
The SessionFactory
is created automatically by Spring and is taking its DB connections from Glassfish connection pool. At the moment I am getting a Hibernate session via SessionFactory.getCurrentSession()
. Then I start transaction, do the work and then commit()
or rollback()
at the end. Do I need to do any other actions like disconnect()
, close()
, flush()
or any others at any time so connections would be properly returned back to the pool or is everything already automatically done by Spring?
With plenty of these methods it is a little confusing for me at the moment to understand when what should be done, maybe someone can point to right direction?
There are three states or Life cycle of objects in Hibernate which are: Transient, Persistent and Detached.
Spring opens a new Hibernate Session at the beginning of the request. These Sessions are not necessarily connected to the database. Every time the application needs a Session, it will reuse the already existing one. At the end of the request, the same interceptor closes that Session.
When you are executing a hibernate query through SessionFactory. getCurrentSession() , Spring performs the necessary task of opening and closing the connection . The SessionFactory you are using in the spring config also calls the config. buildSessionFactory method internally .
In the context of Hibernate's Session, objects can be in one of three possible states: transient, persistent, or detached.
As SessionFactory is created automatically by Spring, Spring framework will take care of closing the connection. Check out Spring Resource Management
If you want to check. You can check the log, if you are using logging for your app. It'll be like :
(main) INFO [AnnotationSessionFactoryBean] Closing Hibernate SessionFactory
I get following lines from this link
The main contract here is the creation of Session instances. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. Implementors must be threadsafe.
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