XML配置声明式事务:(基本不用)
需要spring-jdbc 、spring-tx依赖和tx约束,约束可以直接用spring-jdbc ,其中包含spring-tx
声明式事务(xml):为的是无论spring集成什么dao框架,我们不用写事务代码
1.开始将事务管理者配置到核心容器
2.注入数据源
3.配置事务
3.1 tx配置事务规则
事务规则:
name就是方法名 事务规则作用的范围
rollback-for 遇到什么就回滚 默认是异常java.lang.Exception 也可以其他异常
no-rollback-for 遇到什么不回滚 也是一种异常 利于空指针异常时不回滚
timeout 表示事务超时时间 默认为-1 永不超时
read-only 是否是只读事务 默认为false 一般用于查询
isolation 事务隔离级别 一般也是默认
read-uncommitted 读取未提交 脏读
read-committed 读取已经提交 (Oracle默认隔离级别)不可重复读
repeatable-read 可重复读 (Mysql默认隔离级别) 幻读
Serializable 串行化 (最高级)
3.2 aop设置切入点
3.3 aop关联规则和切入点
xml案例:
开始将事务管理者配置到核心容器 并注入数据源
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="datasource"></property>
</bean>
配置事务规则:
<tx:advice id="ad1" transaction-manager="transactionManager">
<tx:attributes>
<!--事务管理作用到的方法-->
<tx:method name="transfer" read-only="true" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>
AOP配置切入点以及切入点和事务规则的关联
<aop:config>
<!--切入点 用于整个类 不具体到某个方法 方法被事务规则圈定了 此时方法用*表示 代表该类所有方法-->
<aop:pointcut id="pt1" expression="execution(* com.ls.service.AccountServiceImpl.*(..))"></aop:pointcut>
<!--切入点和规则关联-->
<aop:advisor advice-ref="ad1" pointcut-ref="pt1"></aop:advisor>
</aop:config>
注解配置声明式事务:
声明式事务(xml):为的是无论spring集成什么dao框架,我们不用写事务代码
1.开始将事务管理者配置到核心容器
2.注入数据源
3.开启注解驱动
4.在方法上添加Transactional注解 属性也和配置文件一样
案例:
开始将事务管理者配置到核心容器 并注入数据源
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="datasource"></property>
</bean>
<!--加载事务管理者驱动-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>