springmvc事务控制批量插入多张表格

@Component
public class SynchronizationDataImpl implements SynchronizationData {
    private static final Logger logger = LoggerFactory.getLogger(SynchronizationDataImpl.class);
    @Autowired
    private ApplicationSumaryMapper applicationSumaryMapper;
    @Autowired
    private ContactPhoneMapper contactPhoneMapper;
    @Autowired
    private MiddleFieldMapper middleFieldMapper;
    @Autowired  //①  注入上下文
    private ApplicationContext context;

    private SynchronizationData synchronizationData;// 新的bean对象可以完成独立的事务
    //通过上下文重新获取bean对象
    @PostConstruct
    private void setSynchronizationData() {
        synchronizationData = (SynchronizationData) context.getBean("synDataTask");
    }

    //需要同步总条数
    private long totalNumber = 0;
    //需要同步的最大进件id;
    private long maxSid = 0;
    //当前已经同步的sid
    private long currentSid = 0;
    private long maxPage = 0;
    //每页删除条数
    private long pageNumber = 500;

    @Override
    public void startSynData() {

        for (; i <= maxPage; ) {
            long time1 = System.currentTimeMillis();
            if (isSynStart(currentSid, maxSid)) {
                List contactList = new ArrayList();
                List middleList = new ArrayList();
                List synDataList = new ArrayList();
                //开始分页查询,这里会开启一个完整的事务我们理解为父事务
                i = synchronizationData.synDataByPage(i, contactList, middleList, synDataList);
                JedisUtil.setString("synData_currentPage", i + "");
            } else {
                //不符合同步条件,啥也不做
                break;
            }
        }


    }

   

    @Transactional
    @Override
    public long synDataByPage(long i, List contactList, List middleList, List synDataList) {

        synDataList = applicationSumaryMapper.getSynData(0, pageNumber, currentSid, maxSid);
        if (synDataList.size() > 0) {

            //遍历集合组装数据
            prepareDataForBatchInsert(contactList, middleList, synDataList);
            try {
                contactPhoneMapper.batchAdd(contactList);//数据库事务A
                middleFieldMapper.batchAdd(middleList); //数据库事务B
                i++;
            } catch (Exception e) {
                throw new RuntimeException();
            }

        }
        return i;

}

}

说明:独立父事务的开启会保证事务A和事务B同时成功才会提交事务,否则会回滚。

你可能感兴趣的:(学习)