Spring进行事务管理一般是有两种操作方式
一是编程式事务管理 二是声明式事务管理
我们一般就使用声明式事务管理
过程:
①Spring配置文件设置
<!--创建连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--创建事务管理器-->
<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>
②添加注解
@Transactional
给注解可以添加在具体的方法上,也可以直接添加在类上,表示该类的所有方法都开启了事务
package com.rongxing.service;
import com.rongxing.bean.HosDistrict;
import com.rongxing.mapper.HosDistrictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class HosDistrictService {
@Autowired
HosDistrictMapper hdm;
/**
* 查询
*/
public HosDistrict selectByPrimaryKey(Integer did){
System.out.println("HosDistrictService selectByPrimaryKey");
HosDistrict hosDistrict = hdm.selectByPrimaryKey(did);
return hosDistrict;
}
/**
*插入
*/
public Integer insert(HosDistrict hosDistrict){
System.out.println("HosDistrictService insert");
Integer insert = hdm.insert(hosDistrict);
// System.out.println(1/0);
return insert;
}
}
同时我们还可以为该注解添加属性
@Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,rollbackFor = IndexOutOfBoundsException.class)
isolation可以指定的事务的隔离级别,总共有四种隔离级别
READ_UNCOMMITTED(1),
READ_COMMITTED(2),
REPEATABLE_READ(4),
SERIALIZABLE(8);
propagation可以指定事务的传播方式,总共有七种传播方式
REQUIRED(0),
SUPPORTS(1),
MANDATORY(2),
REQUIRES_NEW(3),
NOT_SUPPORTED(4),
NEVER(5),
NESTED(6);
还可以指定当抛出哪种异常时,才执行事务回滚 rollbackFor
当我们的方法发生异常时,想让它正常执行下去,同时也能让事务回滚,我们可以创建一个代理类帮助我们处理异常,回滚事务。
package com.proxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@Component
//aspect代理注解
@Aspect
public class ThrowProxy {
//切入点和通知方式
@Around("execution(* com.*.*.*(..))")
public Object aroundMenthod(ProceedingJoinPoint proceedingJoinPoint){
Object res=null;
try {
//执行被代理类方法
res = proceedingJoinPoint.proceed();
} catch (Throwable e) {
//进行手动地事务回滚
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
return res;
}
}