spring transaction
spring 事务的特点
- 提供一致的对于不同的事务管理的api
- 支持声明式事务管理
- 编程事务管理
- 优秀的整合与spring的数据访问
spring 事务管理的api
- org.springframework.transaction.PlatformTransactionManager
事务管理器,不同的应用平台对它进行不同的实现(jdbc、hibernate、jpa)- DataSourceTransactionManager 针对JdbcTemplate、Mybatis开发
- HibernateTransactionManager 针对Hibernate开发
- JpaTransactionManager 针对Jpa开发
- org.springframework.transaction.TransactionDefinition
定义事务的一些信息(隔离、传播、超时、只读)- 隔离
int ISOLATION_DEFAULT = -1; // 使用后端数据库默认的隔离级别(spring 默认) int ISOLATION_READ_UNCOMMITTED = 1; // 不能解决问题,会产生脏读、不可重复读、虚读 int ISOLATION_READ_COMMITTED = 2; // oracle 默认,解决脏读,产生不可重复读、虚读 int ISOLATION_REPEATABLE_READ = 4; // mysql 默认,解决脏读、不可重复读、产生虚读 int ISOLATION_SERIALIZABLE = 8; // 解决所有问题
- 传播
解决两个被事务管理的方法互相调用的问题int PROPAGATION_REQUIRED = 0; // spring 默认,两个操作处于同一事务,如果之前没有事务,新建一个事务 int PROPAGATION_SUPPORTS = 1; // 支持当前事务,如果事务不存在,就不使用事务 int PROPAGATION_MANDATORY = 2; // 支持当前事务,如果事务不存在,就抛出异常 int PROPAGATION_REQUIRES_NEW = 3; // 两个操作处于不同事务 int PROPAGATION_NOT_SUPPORTED = 4; // 以非事务状态运行,如果有事务存在,就挂起当前事务 int PROPAGATION_NEVER = 5; // 以非事务状态运行,如果有事务存在,就抛出异常 int PROPAGATION_NESTED = 6; // 嵌套事务,使用SavaPoint来实现。如果事务回滚,回滚到指定的SavaPoint。它只针对于DataSourceTransactionManager
- 超时
int TIMEOUT_DEFAULT = -1; // 默认值,默认使用数据库默认的超时时间
- 只读
// true/false 选择true时,一般是用在select的时候 boolean isReadOnly();
- 隔离
- org.springframework.transaction.TransactionStatus
描述事务具体的运行状态。在事务运行过程中,得到某个时间点的状态
声明式事务管理
事务管理有两种方式:
方式一:直接编码。不建议使用,具有侵入性。在原有的业务代码的基础上添加事务管理的代码
方式二:使用声明式事务管理。基于aop对目标进行代理,添加around环绕通知。 建议使用
基于xml配置声明式事务
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="c3p0DataSource"/>
</bean>
<!--基于xml配置声明式事务管理方案-->
<!--配置通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transferAccount"/>
</tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
<!--切点-->
<aop:pointcut id="txPointcut" expression="execution(* cn.ade.service.AccountService.transferAccount(..))"/>
<!--通知-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
基于注解配置声明式事务
- 开启注解事务控制
<!--基于注解声明式事务管理方案-->
<tx:annotation-driven transaction-manager="transactionManager"/>
- 在类或者方法上添加@Transactional来实现声明式事务管理