我使用此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
。有没有办法只返回空对象没有这个异常?
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();
您可以使用简化返回语句
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
。
是。无论您的异常源自何处,请将其包装在try/catch
块中,如下所示:
try {
<code that throws exception>
} catch (NoSuchElementException e) {
return new MyObject();
}