【问题标题】:Define what method to call based on value of Optional根据 Optional 的值定义调用什么方法
【发布时间】:2020-05-28 18:56:49
【问题描述】:

是否有可能以某种方式更改下面的代码,以便在没有提供 status 值的情况下返回存储在数据库中的所有 PaymentLog 对象,而不是仅返回 status 等于 404 的对象?基本上,如果没有提供status变量来调用服务层中的另一个方法logService.getAllPaymentLogs()

@GetMapping(Endpoints.LOGS.PAYMENT_LOGS)
public Page<PaymentLog> getPaymentLog(@RequestParam Optional<Integer> status) {
    return logService.getPaymentLogStatus(status.orElse(404), PageRequest.of(0, 10));
}

这些是getPaymentLogStatus()getAllPaymentLogs

@Override
public Page<PaymentLog> getPaymentLog(Pageable pageable) {
    return paymentLogRepository.getAllBy(pageable);
}

@Override
public Page<PaymentLog> getPaymentLog(int status, Pageable pageable) {
    return paymentLogRepository.getAllByStatus(status, pageable);
}

【问题讨论】:

  • 你的paymentLogRepository 有类似getAll() 的方法吗?
  • status.map(s -&gt; getPaymentLog(s, page)).orElseGet(() -&gt; getPaymentLog(page))?
  • 谢谢。我假设“s”是“status”的值。
  • @Dc235 是的,在 lambda 中随心所欲地调用它,它只是 Optional 中的元素

标签: java spring spring-boot pagination option


【解决方案1】:

@123 在评论环节回答了问题:

status.map(s -> getPaymentLog(s, page)).orElseGet(() -> getPaymentLog(page))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    相关资源
    最近更新 更多