You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复删除CounterParty时抛出的EmptyResultDataAccessException异常?

问题修复方案

问题根源

你的代码里调用counterPartyRepository.getById(counterParty.getId())判断ID是否存在,但Spring Data JPA的getById方法在目标ID不存在时,不会返回null,而是直接抛出EmptyResultDataAccessException,导致else分支根本不会执行,异常直接向外抛出。另外,循环里的message变量会被每次循环覆盖,最终只能返回最后一条数据的处理结果,无法体现批量操作的整体状态。

修复后的代码

public String deleteCounterParty(List<CounterParty> counterParties) {
    StringBuilder messageBuilder = new StringBuilder();
    for(CounterParty counterParty : counterParties) {
        if (counterParty.getId() != null) {
            if (counterPartyRepository.existsById(counterParty.getId())) {
                counterPartyRepository.deleteById(counterParty.getId());
                messageBuilder.append("ID: ").append(counterParty.getId()).append(" deleted successfully; ");
            } else {
                messageBuilder.append("ID: ").append(counterParty.getId()).append(" not found; ");
            }
        } else {
            messageBuilder.append("Skipped a CounterParty with null ID; ");
        }
    }
    // 移除末尾多余的分号和空格
    if (messageBuilder.length() > 0) {
        messageBuilder.setLength(messageBuilder.length() - 2);
    }
    return messageBuilder.length() == 0 ? "No valid CounterParty to process" : messageBuilder.toString();
}

关键修改点

  • 用existsById替代getById:existsById仅判断ID是否存在,返回布尔值,不会抛出异常,完美适配判断需求。
  • 改用StringBuilder收集结果:避免单变量被覆盖,能完整记录每一条数据的处理状态。
  • 增加对null ID的处理:跳过ID为空的对象,避免无效操作。

内容的提问来源于stack exchange,提问作者green

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:09:26