我以下列方式使用Optional进行事务管理
EmployeeBo transactionResult =
Optional.ofNullable(service.save(employeeBo))
.filter(o -> o.getId() !=null && o.getId() > 0)
.map(employeeBo1 -> {
Boolean resultFileController =
Optional.ofNullable(fileController.increaseUsedById(Authorization, fileIds))
.filter(o1 -> o1.getStatusCode().equals(HttpStatus.OK))
.map(fileResponse -> {
ResponseEntity<ObjectResponseBo> userResponse = null;
try {
userResponse = userService.addUser(Authorization, populateUser(employeeBo.getId()));
} catch (Exception e) {
e.printStackTrace();
}
Boolean resultUserService = Optional.ofNullable(userResponse)
.filter(o2 -> o2.getStatusCode().equals(HttpStatus.CREATED))
.map(o3 -> {
logger.debug(()-> "User Added successfully !! ");
return true;
}).orElseGet(() -> {
logger.debug(()->"User Not Added successfully !! ");
return false;
});
//Rollback File
if (resultUserService == Boolean.FALSE) {
fileController.decreaseUsedById(Authorization, fileIds);
logger.debug(()->"File Rollbacked !! ");
return false;
}
logger.debug(()->"File Update successfully !! ");
return true;
}).orElseGet(() -> {
logger.debug(()->"File record updation failed !! ");
return false;
});
//Rollback Employee
if (resultFileController == Boolean.FALSE) {
service.delete(employeeBo1.getId());
logger.debug(()->"Rollback Company successfully !! ");
return employeeBo;
}
logger.debug(()->"Company Saved successfully !! ");
return employeeBo1;
}).orElseGet(() -> {
logger.debug(()->"Company Saved failed !! ");
return null;
});
工作正常。但是代码不容易被读作可选内部选项等。有什么另一种方法来实现这种回滚链接?好像任何交易都失败了,这是我以前的交易失败了,等等......
任何其他好的解决方案?