how spring manage hibernate session lifecycle

旧时模样 提交于 2020-01-12 05:53:33

问题


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.


回答1:


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.




回答2:


The hibernate.current_session_context_class configuration parameter defines which org.hibernate.context.CurrentSessionContext implementation should be used. For backwards compatibility, if this configuration parameter is not set but a org.hibernate.transaction.TransactionManagerLookup is configured, Hibernate will use the org.hibernate.context.JTASessionContext., which you can also configure by setting the property and using the shortform as 'jpa'.

So by default, you are using 'jpa' - you can override it by defining a property like.

<prop key="hibernate.current_session_context_class">managed</prop>

Read this for complete information on contextual sessions.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/architecture.html#architecture-current-session



来源:https://stackoverflow.com/questions/10680364/how-spring-manage-hibernate-session-lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!