导入tx和aop命名空间
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
定义事务采用JDBC管理事务:
<!--定义事务采用JDBC管理事务-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice> -->
tx:method其他属性:
- timeout:事务超时时间,允许事务运行的最长时间,以秒为单位。默认值为-1,表示不超时
- read-only:事务是否为只读,默认值为false
- rollback-for:设定能够触发回滚的异常类型Spring默认只在抛出runtime exception时才标识事 务回滚 可以通过全限定类名指定需要回滚事务的异常,多个类名用逗号隔开
- no-rollback-for:设定不触发回滚的异常类型
- Spring默认checked Exception不会触发事务回滚 可以通过全限定类名指定不需回滚事务的异常,多个类名用英文逗号隔开
propagation事务传播机制:
- propagation_requierd(默认):如果当前没有事务,就新建一个事务,如果已存在一个事务中, 加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂 起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与 propagation_required类似的操作
定义切面:
<!-- 定义切面 -->
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.hz.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
事务注解
<!--事务注解 开启注解 -->
<tx:annotation-driven />