用空对象替换 SQL 异常

Replace SQL Exception with empty object

我使用此 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。有没有办法 return 只清空对象而不出现此异常?

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();

是的。无论您的异常来自何处,都将其包装在 try/catch 块中,如下所示:

try {
    <code that throws exception>
} catch (NoSuchElementException e) {
    return new MyObject();
}

您可以使用

简化您的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