spring mvc中配置事务

事务的配置

事务有两种方式,下面介绍编程式事务。(aop与事务的结合,aop需要的pom.xml配置可以去网络获取)
在spring -tx.xml头中加入命名空间 。

xmlns:tx="http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd

然后继续加入

   <tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="insertInto" propagation="REQUIRED"
				read-only="false" rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>
    <!-- 从spring获取事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

REQUIRED解释
如果在同一个service类中定义的两个方法, 内层REQUIRES_NEW并不会开启新的事务,save和update中回滚都会导致整个事务的回滚 。
如果在不同的service中定义的两个方法, 内层REQUIRES_NEW会开启新的事务,并且二者独立,事务回滚互不影响 。

rollback-for解释
Spring框架的事务基础架构代码将默认地 只 在抛出运行时和unchecked exceptions时才标识事务回滚。 也就是说,当抛出个 RuntimeException 或其子类例的实例时。(Errors 也一样 - 默认地 - 标识事务回滚。)从事务方法中抛出的Checked exceptions将 不 被标识进行事务回滚。

然后在spring-mvc.xml中添加命名空间,在之后加入Aop配置。

    <!-- 开启Aop-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
	<!-- 配置切入方法-->
	<aop:config proxy-target-class="true">
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service.*.*(..))" />
	</aop:config>

猜你喜欢

转载自blog.csdn.net/qq_20143059/article/details/113339139