控制器中的Spring Roll Back异常

时间:2018-10-16 10:07:42

标签: spring exception-handling

我想回退控制器范围内的异常,因为我在控制器中调用了某些服务,并且希望保持这些服务独立。我的代码如下:

@RestController
@RequestMapping("/admin/corporation")
public class AdminCorporationController {
    private final AdminCorporationService adminCorporationService;
    private final OperateRecordService operateRecordService;
    private final AdminIdentityService adminIdentityService;

    @Autowired
    public AdminCorporationController(AdminCorporationService adminCorporationService, OperateRecordService operateRecordService, AdminIdentityService adminIdentityService) {
        this.adminCorporationService = adminCorporationService;
        this.operateRecordService = operateRecordService;
        this.adminIdentityService = adminIdentityService;
    }

    @HasRole({ROLE_SUPER_ADMIN, ROLE_MAIN_ADMIN})
    @PostMapping("/addCorporation")
    public Map<Object, Object> addCorporation(@RequestBody JSONObject jsonObject) throws ExecutionException, InterruptedException {
        Corporation corporation = (Corporation) JSONObject.toBean(jsonObject.getJSONObject("corporation"), Corporation.class);
        CorporationStaff corporationLeader = (CorporationStaff) JSONObject.toBean(jsonObject.getJSONObject("corporationLeader"), CorporationStaff.class);
        //add Corporation method
        CompletableFuture<String> addCorporationFuture = adminCorporationService.addCorporation(corporation);
        corporationLeader.setCorporationId(addCorporationFuture.get());
        //for example, exception happened in this service method, I want to roll back the two serivce method together.
        //add Corporation Staff method
        CompletableFuture<Void> addIdentitiesFuture = adminIdentityService.addIdentities(new CorporationStaff[]{corporationLeader}, IDENTITY_TYPE_CORPORATION_STAFF);
        CompletableFuture.allOf(addCorporationFuture, addIdentitiesFuture).get();
        return ResponseUtil.success(null, null);
    }
}

当前的情况是我只能回滚其中一种方法。如果成功添加了公司但添加职员失败,则公司信息仍会添加到数据库中,但是当职员添加失败时,我想回滚添加的公司信息。有什么办法吗?非常感谢你! :)

0 个答案:

没有答案