问题场景
在一个@service方法上加上 @Transactional(rollbackFor = Exception.class)注解后,发现该方法中调用的另一个方法中抛出异常,在调用该方法之前的对表的修改未回滚,生效了。
问题代码:
/**
* @Description: 修改任务状态
* @Author: gj
* @Date: 2020/4/2
*/
@Transactional(rollbackFor = Exception.class)
public void updateTaskState(Integer userId, String id, Integer type, Integer currentUserId) {
designService.updateTaskState(userId, id, type, currentUserId);
if (type == 5) {
Optional.ofNullable(designService.getDesignTaskDetail(id)).ifPresent(designTaskDO -> {
WorksDTO worksDTO = new WorksDTO();
worksDTO.setBrandId(designTaskDO.getCustomerId());
worksDTO.setClothingCategoryId(designTaskDO.getClothingCategoryId());
worksDTO.setDesigner(designTaskDO.getDesigner());
worksDTO.setDesignTaskId(designTaskDO.getDesignTaskCode());
worksDTO.setSortId(designTaskDO.getApplicationType().toString());
worksDTO.setCompany(designTaskDO.getCompany());
worksDTO.setCreator(designTaskDO.getCreator());
List<UserFile> userFiles = new ArrayList<>();
List<DesignFileDO> designFileDOList = designService.listFile(id);
if (!designFileDOList.isEmpty()) {
designFileDOList.forEach(file -> {
userFiles.add(new UserFile(file.getName(), 0, file.getOssKeyOriginal(), file.getOssKeyPreview()));
});
worksDTO.setFiles(userFiles);
worksAppService.addBatch(worksDTO);
}
});
}
}
worksAppService.addBatch(worksDTO)中抛异常,但上面的designService.updateTaskState(userId, id, type, currentUserId)修改状态成功了。
解决方法
查阅相关资料发现需要添加配置类,开启mongodb事务。
@Configuration
public class TransactionConfig {
@Bean
MongoTransactionManager transactionManager(MongoDbFactory factory){
return new MongoTransactionManager(factory);
}
}