Spring註解事務配置

Spring的聲明式事務配置很是繁瑣,所以貌似看了很多Spring項目都是使用註解式事務,使用Spring註解式很是方便。只需要進行如下配置:

在applicationContext中配置事務管理器

無論是聲明式事務還是註解式事務,都是需要配置事務管理器的。

	<!-- 事務管理器 -->
	<!-- BEGIN -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- END -->

在applicationContext啓用註解事務

	<!-- 啓用註解事務 -->
	<!-- BEGIN -->
	<tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>
	<!-- END -->

在需要事務的類中使用註解

@Transactional(propagation=Propagation.REQUIRED , rollbackFor = java.lang.Exception.class)
public class TestDaoImpl extends HibernateDaoSupport {

	public void save(Test1 test)
	{
		Session session = this.getSessionFactory().getCurrentSession();
		session.save(test);
	}
}

需要注意的一些問題

拋出no active transaction異常

如果你使用的是Hibernate3整合的話,這個原因一般是因爲配置文件中加了一下的一行配置
				<!--<prop key="hibernate.current_session_context_class">
                    thread
                </prop>  -->

把這行配置去掉。


拋出NoClassDefExeption

這個原因是因爲缺少Jar文件,Spring中需要asm-3.3.jar的支持,如果使用Myecplise IDE是沒有把這個Jar包加入進去的。




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章