我使用此代码通过ID获取商家名称。
@GetMapping("pages")
public Page<WpfPaymentsDTO> pages(@RequestParam(value = "page") int page, @RequestParam(value = "size") int size) {
return wpfPaymentsService.findAll(page, size)
.filter(g -> g.getMerchant_id() != null)
.map(g -> WpfPaymentsDTO.builder()
.id(g.getId())
.status(g.getStatus())
.merchant_id(getMerchantName(g.getMerchant_id()))
.build());
}
private String getMerchantName(Integer id) {
return Optional.ofNullable(id)
.flatMap(i -> merchantService.findById(i))
.map(Merchants::getName)
.orElse("");
}
但是当找不到名称时,我会java.lang.NullPointerException: null at this line: .merchant_id(getMerchantName(g.getMerchant_id()))
,因为值g.getMerchant_id()
null
到数据库中。
有没有办法从对象中过滤几个空值?
只需在类中创建一个方法,类似于返回布尔值的isValid
。您可以在方法中添加任何复杂条件。然后在 filter
中使用该方法。
private boolean isValid() {
return getMerchent_id() != null && getMerchantName(g.getMerchant_id()) != null
}
现在在过滤器中使用此条件。
return wpfPaymentsService.findAll(page, size)
.filter(g -> g.isValid())
它只能是getMerchantName(我认为(,再次检查堆栈跟踪。
private String getMerchantName(Integer id) {
return Optional.ofNullable(id)
.flatMap(i -> merchantService.findById(i))
.filter(Objects::nonNull)
.map(Merchants::getName)
.orElse("");
}
也许是流过度使用的情况。
private String getMerchantName(Integer id) {
return id == null ? ""
: merchantService.findById(id.intValue()) // Stream / Optional?
.filter(Objects::nonNull)
.map(Merchants::getName)
.filter(Objects::nonNull) // When there are null names.
.orElse("");
}