配置声明式事务
1.开启配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/beans/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/beans/spring-tx.xsd
">
<!-- 配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
2. 配置事务属性
<!-- 2. 配置事务属性 -->
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/><!--选择需要处理的方法-->
<tx:method name="select" read-only="true"/>
<tx:method name="delete"/>
</tx:attributes>
</tx:advice>
1.PROPAGATION_REQUIRED(默认实现):当前没有事务则新建事务,有则加入当前事务
2.PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务则以非事务方式执行
3.PROPAGATION_MANDATORY:使用当前事务,如果没有则抛出异常
4.PROPAGATION__REQUIRES_NEW:新建事务,如果当前有事务则把当前事务挂起
5.PROPAGATION_NOT_SUPPORIED:以非事务的方式执行,如果当前有事务则把当前事务挂起
6.PROPAGATION_NEVER:以非事务的方式执行,如果当前有事务则抛出异常
7.PROPAGATION_NESTED:如果当前存在事务,则在嵌套事务内执行,如果当前没有事务,则执行1
aop织入
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* mapper.*.*(..))"/>
<aop:advisor advice-ref="transactionInterceptor" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>