我使用此SQL查询获取简单对象:
@Override
public Optional<PaymentTransactions> paymentTransactionByWpfPaymentId(Integer id) {
String hql = "SELECT t FROM " + PaymentTransactions.class.getName() + " t "
+ " WHERE wppt.wpf_payment_id = :id ";
TypedQuery<PaymentTransactions> query = entityManager.createQuery(hql, PaymentTransactions.class).setParameter("id", id);
List<PaymentTransactions> wpfPayments = query.getResultList();
return wpfPayments.isEmpty() ? Optional.empty() : Optional.of(wpfPayments.get(0));
}
我使用此终点
@GetMapping("/{id}")
public ResponseEntity<List<PaymentTransactionsDTO>> getWpf_reference_transactions(@PathVariable String id) throws NumberFormatException, Exception {
Optional<PaymentTransactions> tnx = wpfPaymentsService.paymentTransactionByWpfPaymentId(Integer.parseInt(id));
if(tnx.get().getId() != 0) {
return ResponseEntity.ok(transactionService
.get(Integer.valueOf(tnx.get().getId())).stream()
.collect(Collectors.toList()));
}
return ResponseEntity.notFound().build();
}
但是当数据库为空时,我得到java.util.NoSuchElementException: No value present
。有没有一种方法可以只返回没有该异常的空对象?
答案 0 :(得分:2)
您可以使用以下方式简化return语句
return tnx.map(PaymentTransactions::getId)
.filter(id -> id != 0)
.map(id -> transactionService.get(id)
.stream()
.collect(Collectors.toList()))
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
一种更清洁的方法。
也是这个
id -> transactionService.get(id)
.stream()
.collect(Collectors.toList()
可以成为
id -> new ArrayList<>(transactionService.get(id)))
所以你有
tnx.map(Transaction::getId)
.filter(id -> id != 0)
.map(id -> new ArrayList<>(transactionService.get(id)))
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
我也怀疑你需要
id -> new ArrayList<>(transactionService.get(id))
相反,这足够了
id -> transactionService.get(id)
因为您根本无法触摸List
。
答案 1 :(得分:1)
Optional.get()
将抛出NoSuchElementException - if there is no value present
,因此请使用isPresent
来知道该值是否为可选值
if(tnx.isPresent() && tnx.get().getId() != 0) {
return ResponseEntity.ok(transactionService
.get(Integer.valueOf(tnx.get().getId())).stream()
.collect(Collectors.toList()));
}
return ResponseEntity.notFound().build();
答案 2 :(得分:0)
是的。无论异常来自何处,都将其包装在try/catch
块中,如下所示:
try {
<code that throws exception>
} catch (NoSuchElementException e) {
return new MyObject();
}