Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring + Hibernate session lifecycle

Tags:

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?

like image 358
Laimoncijus Avatar asked Jan 04 '12 08:01

Laimoncijus


People also ask

What is life cycle of session in Hibernate?

There are three states or Life cycle of objects in Hibernate which are: Transient, Persistent and Detached.

How does Spring manage Hibernate sessions?

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.

What is session in spring Hibernate?

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 .

How many stages are there in session in Hibernate?

In the context of Hibernate's Session, objects can be in one of three possible states: transient, persistent, or detached.


1 Answers

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.

like image 90
Nandkumar Tekale Avatar answered Sep 21 '22 18:09

Nandkumar Tekale