编程式事务实现/声明式事务失效场景和解决

编程式事务之手动提交

package com.csw.shuanfa.CodeImprove.Transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 */
@RestController
@RequestMapping("Transation")
public class PersonTransation {

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @RequestMapping("show")
    public void show() {
        TransactionStatus transactionStatus = platformTransactionManager.getTransaction(new DefaultTransactionDefinition());

        try {
            System.out.println(">>>>>>数据库操作");
        } catch (Exception e) {//放开异常范围
            platformTransactionManager.rollback(transactionStatus);
            throw e;
        }
        //全部成功在提交
        platformTransactionManager.commit(transactionStatus);
    }
}

编程式事务自动提交

package com.csw.shuanfa.CodeImprove.Transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 【编程式事务】
 */
@RestController
@RequestMapping("TransactionAuto")
public class PersonTransationAutoCommit {
    @Autowired
    private TransactionTemplate transactionTemplate;

    @RequestMapping("show")
    public void show(String name) {
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        System.out.println("======>show...");

        transactionTemplate.executeWithoutResult(status -> {//无返回值
            System.out.println(">>>>>>数据库操作");

            transactionTemplate.execute(status1 -> {//有返回值
                System.out.println(">>>>>>数据库操作");
                return null;
            });

        });
    }
}

声明式事务

@Transactional(rollbackFor = Exception.class)
事务失效场景分为
1、方法是用private 或者final修饰的
2、cat之后没有抛异常或者抛出了异常不在回滚异常中
3、调用事务注解的方法不是用的工厂调用的
如
 this.m2("1", "m1");

解决可以换成
  this.userService.m2("3", "m3");
或者用编程式事务
 this.transactionTemplate.executeWithoutResult(action -> {
            this.m2("4", "m4");
        });
或者
 //通过Spring提供的工具类AopContext.currentProxy(),可以获取当前代理对象,将类型强制转换为UserService,然后调用m2方法,事务也会生效
        UserService as = (UserService) AopContext.currentProxy();
        as.m2("5", "m5");

####看事务有没有生效,看有没有经过这个方法
org.springframework.transaction.interceptor.TransactionInterceptor#invoke

如何解决发生的死锁可以看这个//www.greatytc.com/p/5dbcc9ebfd7f

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容