【问题标题】:Replace SQL Exception with empty object用空对象替换 SQL 异常
【发布时间】:2019-08-12 20:16:15
【问题描述】:

我使用这个 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。有没有办法在没有这个异常的情况下只返回空对象?

【问题讨论】:

  • 我还为 Collectors.toList 部分添加了简化,这似乎不需要。

标签: java jpa jpa-2.0


【解决方案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】:

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

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

    【讨论】:

      【解决方案3】:

      您可以使用以下方法简化您的退货声明

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-30
        • 2011-08-07
        • 1970-01-01
        • 2018-06-07
        • 2021-04-22
        相关资源
        最近更新 更多