1. 程式人生 > >使用ssh出現 Could not obtain transaction-synchronized Session for current thre情況

使用ssh出現 Could not obtain transaction-synchronized Session for current thre情況

這個除錯是基於Hibernate4 的getSessionFactory().getCurrentSession()那個Hibernate3的HibernateTemplate().get(entityClazz, id);也適合,如果出現下面的bug

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thre

是因為我們未對Service層加上事務管理

我們應該在applicationContext.xml中配置

<!-- 配置Hibernate的區域性事務管理器,使用HibernateTransactionManager類 並注入SessionFactory的引用 -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager"
		p:sessionFactory-ref="sessionFactory" />


注意

<!-- 可有可無 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
	<!-- 配置事務增強處理Bean,指定事務管理器 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<!-- 用於配置詳細的事務語義 -->
		<tx:attributes>
			<!-- 所有以'get'開頭的方法是read-only的 -->
			<tx:method name="get*" read-only="true" />
			<!-- 其他方法使用預設的事務設定 -->
			<tx:method name="*" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<!-- 配置一個切入點,匹配empManager和mgrManager 兩個Bean的所有方法的執行 -->
		<aop:pointcut id="leePointcut"
			expression="bean(customerDoDishes) or bean(customerDoMessage) or bean(customerDoNotice) or bean(customerDoOrder) or bean(customerDoOwn) or bean(commonDoDishes)" />
		<!-- 指定在leePointcut切入點應用txAdvice事務增強處理 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="leePointcut" />
	</aop:config>
<