【发布时间】:2020-11-16 06:55:26
【问题描述】:
我正在使用 Hibernate 在 Spring Boot 中开发 REST API。
我的控制器中有这个功能
@PostMapping("/profile")
public ResponseEntity<String> saveProfile(@Valid @RequestBody SaveProfileVM saveProfileVM,
BindingResult bindingResult)
throws JsonProcessingException {
if (bindingResult.hasErrors()) return super.fieldExceptionResponse(bindingResult);
Profile profile;
boolean optimisticLockException = true;
int retryCount = 0;
do {
try {
profile = accountService.saveProfile(saveProfileVM.getAccountId(),
saveProfileVM.getName(),
saveProfileVM.getEmail());
optimisticLockException = false;
retryCount++;
} catch (ObjectOptimisticLockingFailureException exception) {
retryCount++;
System.out.println(exception.getMessage());
}
} while (optimisticLockException && retryCount < MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT);
return ResponseEntity.status(HttpStatus.OK).body(objectMapper.writeValueAsString(profile));
}
而MAX_OPTIMISTIC_LOCK_EXCEPTION_RETRY_COUNT 是 3
我不想在需要检查ObjectOptimisticLockingFailureException的每个方法中重复do..while and try..catch blocks
do {
try{}
catch{}
} while()
有什么方法可以将accountService.saveProfile() 传递给具有do..while and try..catch block 的通用方法,这样我就不必将块复制并粘贴到我需要的每个方法中?
每个控制器都扩展了一个 BaseController,所以在 BaseController 中有通用方法可能会更好?
@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {
请大家给个意见好吗?
【问题讨论】:
标签: spring-boot function hibernate lambda controller