首先是出问题的代码
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(); } }
发表回复