XanderYe的个人小站

AService中开启线程调用BService方法导致查不到数据的问题

首先是出问题的代码

public class AService {
    @Autowired
    private BService bService;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void cMethod() {
        // 执行插入业务
        ……
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> bService.dMethod());
        executorService.shutdown();
    }
}

public class BService {
    
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void dMethod() {
        // 这里执行查询会查不到刚刚插入的数据
        ……
    }
}

解决方法:在开启多线程前手动提交事务

public class AService {
    @Autowired
    private BService bService;
    @Autowired
    DataSourceTransactionManager transactionManager;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void cMethod() {
        // 获取事务定义
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        // 设置事务隔离级别,开启新事务
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        // 获得事务状态,相当于开启事物
        TransactionStatus transactionStatus = transactionManager.getTransaction(def);
        // 执行插入业务
        ……
        // 手动提交事务 防止线程中另一个service的方法获取不到提交的数据
        transactionManager.commit(transactionStatus);
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(() -> bService.dMethod());
        executorService.shutdown();
    }
}
赞赏
没有标签
首页      JAVA      AService中开启线程调用BService方法导致查不到数据的问题

发表回复

textsms
account_circle
email
0 + 34 = ?
verified user

 

XanderYe的个人小站

AService中开启线程调用BService方法导致查不到数据的问题
首先是出问题的代码 public class AService { @Autowired private BService bService; @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.cla…
扫描二维码继续阅读
2020-06-17