Spring – how spring manage hibernate session lifecycle

hibernatelifecyclesessionspring

Spring is used in our team's Java EE project, and hibernate is used for underlying ORM.

transactionManager is set like below:

<bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> 

sessionFactory is set like below:

<bean id="sessionFactory"  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan"
value="com.company.model" />
<property name="hibernateProperties">

<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.jdbc.fetch_size=50
</value>
</property>
</bean>

my quesiton is thoughtout the whole setting, I didn't see any property setting for hibernate session lifecycle.In hibernate reference, Contextual sessions was introduced and it's said that there three implementations of CurrentSessionContext.

  1. JTA 2.Thread 3.Managed

How do I know which implementation has been used.Maybe by Spring, but I've no idea.

Best Answer

The SessionFactory is created by Spring using given dataSource and is taking its DB connections from connection pool. We get a Hibernate session via SessionFactory.getCurrentSession(). then start transaction, do the work and then commit() or rollback(), and at the end close the connection(connection object will be returned to the pool). Hibernate session factory will be destroyed/closed when we either stop application or shutdown the server. And By default, Thread implementations of CurrentSessionContext will be used, if you use HibernateTransactionManager. If you want to use, jta implementation: you have to use "JtaTransactionManager" as a Transaction manager.

Related Topic