一、什么是事务
1、从保证内容的一致性,以及事务的四大特性(原子性、一致性、隔离性和持久性)出发进行讲解。
2、项目中怎么用事务的:
事务的分类:
编程式事务
声明式事务:xml声明、注解声明
3、哪里用到Aop
可以讲下事务,前置通知开启事务,后置通知提交事务,捕获通知回滚事务
使用声明式事务注意事项
事务是程序运行如果没有错误,会自动提交事物,如果程序运行发生异常,则会自动回滚。
如果使用了try捕获异常时.一定要在catch里面手动回滚。
事物手动回滚代码
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
二、AOP的实现原理
- 静态代理:需要生产目标代理对象 (不推荐)
- 动态代理:不需要生产目标代理对象
1、动态代理分为:jdk动态代理、CGLIB
jdk代理需要接口。CGLIB需要子类实现(基于ASM字节码包装的类库)。
三、静态代理实例
1、创建接口类
public interface UserService {
void add();
}
2、创建实现类
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("插入数据库");
}
}
3、创建静态代理类
public class UserStaticProxy {
private UserService userService;
public UserStaticProxy(UserService userService) {
this.userService = userService;
}
public void add() {
System.out.println("静态代理 开启事务");
userService.add();
System.out.println("静态代理 结束事务");
}
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
UserStaticProxy userStaticProxy = new UserStaticProxy(userService);
userStaticProxy.add();
}
}
4、打印日志结果
静态代理 开启事务
插入数据库
静态代理 结束事务
四、动态代理
1、jdk动态代理
public class InvocationHandlerImpl implements InvocationHandler {
private Object target;
public InvocationHandlerImpl(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
System.out.println("开始调用jdk动态代理");
result = method.invoke(target, args);
System.out.println("结束调用jdk动态代理");
return result;
}
public static void main(String[] args) {
UserService userService = new UserServiceImpl();
InvocationHandlerImpl invocationHandler = new InvocationHandlerImpl(userService);
ClassLoader loader = userService.getClass().getClassLoader();
Class<?>[] interfaces = userService.getClass().getInterfaces();
UserService newProxyInstance = (UserService) Proxy.newProxyInstance(loader, interfaces, invocationHandler);
newProxyInstance.add();
}
}
五、Spring事务
1、Spring分为编程事务和声明事务。其中声明事务原理是使用编程事务+反射进行包装的。
2、事务特点:ACID特点即(原子性、一致性、隔离性、持久性)
3、应用场景:日志、安全、
六、手写Spring事务框架
1、dao层
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void add(String username, String address) {
String sql = "INSERT INTO lz(username, address) VALUES(?,?)";
int update = jdbcTemplate.update(sql, username, address);
System.out.println("updateResult:" + update);
}
}
2、Service层
public interface UserService {
void add();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void add() {
userDao.add("test1", "xian");
// int i = 1 / 0;
userDao.add("test2", "beijing");
}
}
3、自定义事务工具类
@Component
public class TransacUtil {
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
public TransactionStatus begin() {
TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
return transaction;
}
public void commit(TransactionStatus status) {
dataSourceTransactionManager.commit(status);
}
public void rollback(TransactionStatus status) {
dataSourceTransactionManager.rollback(status);
}
}
4、Aop切面类
@Component
@Aspect
public class AopTransc {
@Autowired
public TransacUtil transacUtil;
@Around("execution(* com.liu.service.UserService.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("开始事务");
TransactionStatus status = transacUtil.begin();
proceedingJoinPoint.proceed();
transacUtil.commit(status);
System.out.println("提交事务");
}
@AfterThrowing("execution(* com.liu.service.UserService.add(..))")
public void afterThrowing() {
System.out.println("异常通知 开始回滚");
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
5、测试类
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
UserService service = (UserService) applicationContext.getBean("userServiceImpl");
service.add();
}
六、手写注解式事务
主要步骤:
a、获取被代理的方法
b、检测是否开启了事务
c、开启事务
d、执行方法
e、提交事务具体代码
1、定义事务注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExTransactionAnnotation {
}
2、定义事务工具类
/**
* Spring默认是单例,这会导致线程安全问题,所以增加Scope注释
*/
@Component
@Scope("prototype")
public class TransacUtil {
@Autowired
private DataSourceTransactionManager dataSourceTransactionManager;
private TransactionStatus transaction;
public TransactionStatus begin() {
transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
return transaction;
}
public void commit() {
dataSourceTransactionManager.commit(transaction);
}
public void rollback() {
dataSourceTransactionManager.rollback(transaction);
}
}
3、定义切面类
@Aspect
@Component
public class AopTransactionAnnotation {
@Autowired
private TransacUtil transacUtil;
@Around("execution(* com.liu.service.*.*(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
ExTransactionAnnotation exTransaction = getExTransaction(proceedingJoinPoint);
TransactionStatus transactionStatus = begin(exTransaction);
proceedingJoinPoint.proceed();
commit(transactionStatus);
}
@AfterThrowing("execution(* com.liu.service.UserService.add(..))")
public void afterThrowing() {
System.out.println("异常通知 开始回滚");
transacUtil.rollback();
}
/**
* 开启事务
* @param exTransaction
* @return
*/
private TransactionStatus begin(ExTransactionAnnotation exTransaction) {
if (exTransaction == null) {
return null;
}
System.out.println("开启事务 。。。");
return transacUtil.begin();
}
/**
* 提交事务
* @param transactionStatus
*/
private void commit(TransactionStatus transactionStatus) {
if (transactionStatus != null) {
System.out.println("提交事务。。。");
transacUtil.commit();
}
}
/**
* 获取事务注解代理类
* @param proceedingJoinPoint
* @return
* @throws NoSuchMethodException
*/
private ExTransactionAnnotation getExTransaction(ProceedingJoinPoint proceedingJoinPoint) throws NoSuchMethodException {
String name = proceedingJoinPoint.getSignature().getName();
Class<?> classes = proceedingJoinPoint.getTarget().getClass();
Class<?>[] par =( (MethodSignature)proceedingJoinPoint.getSignature()).getParameterTypes();
Method method = classes.getMethod(name, par);
ExTransactionAnnotation declaredAnnotation = method.getDeclaredAnnotation(ExTransactionAnnotation.class);
if (declaredAnnotation == null) {
return null;
}
return declaredAnnotation;
}
}