【发布时间】:2021-11-11 23:56:34
【问题描述】:
我有下面的Java 11 方法,它由控制器调用,其中ID 是必需的参数,status,version 是可选参数。我不得不编写多个repository 方法来根据这些参数获取记录。我想知道是否有更好/更有效的方法来重构这种方法而无需 if/else 阶梯?
@Override
@Transactional(transactionManager = "customTransactionManager")
public Optional<String> getInformation(UUID id, Status status, Long version) {
try {
Preconditions.checkNotNull(id, ID_MUST_BE_NOT_NULL_MSG);
if (status != null && version != null) {
return repository.findByIdAndVersionAndStatus(id, version, status);
} else if (status != null) {
return repository.findFirstByIdAndStatus(id, status);
} else if (version != null) {
return repository.findFirstByIdAndVersion(id, version);
} else {
return repository.findFirstByIdOrderByIdDesc(id);
}
} catch (Exception e) {
log.error(e);
throw new CustomException(MessageFormat.format(PUBLIC_ERROR_MESSAGE, id));
}
}
【问题讨论】:
标签: spring spring-boot spring-data-jpa java-11