今天处理一个需求时,有个for循环,每次循环都会去调用其他项目然后根据结果删除和新增数据,这里有个demo
public void save() {
for (int i = 0; i< 10; i++){
SysApiLogEntity apiLogEntity = new SysApiLogEntity();
apiLogEntity.setRequestId(RandomUtils.generateString(20));
apiLogEntity.setRequestParam("432432");
apiLogEntity.setRequestUrl("测试=========="+i);
apiLogEntity.setRequestNm("crm数据清洗");
apiLogEntity.setCreateTime(LocalDateTime.now());
try {
SysRequestInfoEntity sysRequestInfoEntity = new SysRequestInfoEntity();
sysRequestInfoEntity.setRequestId("测试事务-=========" + i);
sysRequestInfoEntity.setSysId("32323");
sysRequestInfoEntity.setDealStat(0);
sysRequestInfoEntity.setCreateTime(LocalDateTime.now());
sysRequestInfoEntity.setUpdateTime(LocalDateTime.now());
sysRequestInfoEntity.setBusiId("32434");
sysRequestInfoService.save(sysRequestInfoEntity);
if (i == 5){
int j = 1/0;
}
}catch (Exception e){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}finally {
iSysApiLogService.save(apiLogEntity);
}
}
}
希望遇到异常只回滚那一次循环的操作,而不是把整个for循环都回滚。
这样在catch中操作,会回滚所有的。
解决方法:把每一次循环的单独提出来一个service接口
@Override
public void save1() {
for (int i = 0; i< 10; i++){
service.save(i);
}
}
@Override
@Transactional
public void save(int i) {
SysApiLogEntity apiLogEntity = new SysApiLogEntity();
apiLogEntity.setRequestId(RandomUtils.generateString(20));
apiLogEntity.setRequestParam("432432");
apiLogEntity.setRequestUrl("测试=========="+i);
apiLogEntity.setRequestNm("crm数据清洗");
apiLogEntity.setCreateTime(LocalDateTime.now());
try {
SysRequestInfoEntity sysRequestInfoEntity = new SysRequestInfoEntity();
sysRequestInfoEntity.setRequestId("测试事务-=========" + i);
sysRequestInfoEntity.setSysId("32323");
sysRequestInfoEntity.setDealStat(0);
sysRequestInfoEntity.setCreateTime(LocalDateTime.now());
sysRequestInfoEntity.setUpdateTime(LocalDateTime.now());
sysRequestInfoEntity.setBusiId("32434");
sysRequestInfoService.save(sysRequestInfoEntity);
if (i == 5){
int j = 1/0;
}
}catch (Exception e){
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}finally {
iSysApiLogService.save(apiLogEntity);
}
}