前言:为了能更深入理解事务的机制,所以需要学习一下"手动挡"的事务实现原理。
其实像我们公司自己内部的框架的话,因为是向分布式架构的发展,所以dao层都是被封装成jar包引用了,内部实现spring JdbcTemplate的方式。
还有就是,dao层被封装,并且用try...catch..挡住了异常的抛出。这个时候就需要派上手动事务进行处理了。废话不说,直接干。
实现手动事务步骤:(把思想理解,代码的实现可以百度就行了)
- 自定义事务注解的创建
- 获取spring 的事务管理,创建事务工具类:MyTransactionUtil,其中
- 编写事务的begin()-----返回事务状态TransactionStatus
- 编写事务的commit(TransactionStatus status)方法
- 编写事务的rollback()方法---在抛异常时进行手动回滚
- 实现spring aop,使用@Around,@AfterThrowing 两个注解附带的方法实现。
- 测试CRUD中的C,U
伸手党看下面,具体代码实现如下:
1.util
package com.example.myaop.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
@Service
public class TransactionManagerUtil {
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
// 开启事务
public TransactionStatus begin() {
TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
return transaction;
}
// 提交事务
public void commit(TransactionStatus transactionStatus) {
dataSourceTransactionManager.commit(transactionStatus);
}
// 回滚事务
public void rollback(TransactionStatus transactionStatus) {
dataSourceTransactionManager.rollback(transactionStatus);
}
}
2.
package com.example.myaop.aop;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyTransaction {
}
3.aop
@Aspect
@Component
public class WebLogAspect {
// @Pointcut("execution(public * com.example.myaop.controller..*.*(..))")
//@Pointcut("execution(public * com.example.myaop.service..*.*(..))")
@Autowired
private TransactionManagerUtil transactionManagerUtil;
@Pointcut("@annotation(com.example.myaop.aop.MyTransaction)")
public void webLog(){}
@Around("webLog()")
public void aroundMethod(ProceedingJoinPoint point) throws Throwable {
System.out.println("hahah before..");
TransactionStatus begin = transactionManagerUtil.begin();
point.proceed();
transactionManagerUtil.commit(begin);
System.out.println("hahah end..");
}
@AfterThrowing("webLog()")
public void afterThrow(){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
4.使用
@MyTransaction
public String insertUser(){
MyAopEntity entity = new MyAopEntity();
entity.setAge(1);
entity.setSex("1");
entity.setName("chen3");
myAopEntityMapper.insert(entity);
//int i = 1/0;
MyAopEntity entity2 = new MyAopEntity();
entity2.setAge(12);
entity2.setSex("2");
entity2.setName("chen32");
myAopEntityMapper.insert(entity2);
return "11";
}