You need to enable JavaScript to run this app. Java CodeList按operation属性增删元素时DELETE操作失效问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Java CodeList按operation属性增删元素时DELETE操作失效问题咨询

问题根因

当前逻辑合并请求数据与存量数据后,使用仅按key比较的TreeSet去重时,同key的请求带DELETE标记的实例会被更早加入集合的存量无operation属性的实例覆盖,导致DELETE标记丢失,过滤阶段被默认设置为ADD操作保留,不符合预期。另外原代码中的exceptionMessagesList如果是类成员变量,会存在多线程并发调用时的数据混乱问题,建议改为方法内局部变量。

修复方案

调整数据合并逻辑,优先保留请求中的实例,仅合并请求中未出现过key的存量数据,修改后的prepareChangeObject方法如下:

private static CodeList prepareChangeObject(CodeList codeList, CodeList existingCodeList, boolean dataExists)
        throws EntityValidationException {
    // 方法内定义异常列表,避免线程安全问题
    List<ExceptionMessage> exceptionMessagesList = new ArrayList<>();
    CodeList updatedCodeList = new CodeList();
    BeanUtils.copyProperties(codeList, updatedCodeList);

    // 1. 先将请求中的data按key存入map,优先级最高
    Map<String, CodeListData> reqDataMap = updatedCodeList.getData().stream()
            .collect(Collectors.toMap(CodeListData::getKey, Function.identity()));

    // 2. 合并存量数据,仅添加请求中不存在的key对应的存量实例
    for (CodeListData existData : existingCodeList.getData()) {
        if (!reqDataMap.containsKey(existData.getKey())) {
            reqDataMap.put(existData.getKey(), existData);
        }
    }

    // 3. 过滤逻辑保持对齐原规则,先处理operation再过滤
    List<CodeListData> finalData = reqDataMap.values().stream()
            .sorted(Comparator.comparing(CodeListData::getKey)) // 保留原排序逻辑
            .filter(data -> {
                if (data.getOperation() == null) {
                    data.setOperation(MetaConstants.OPERATION_ADD);
                }
                if (MetaConstants.OPERATION_DELETE.equals(data.getOperation())) {
                    if (dataExists) {
                        exceptionMessagesList.add(
                                new ExceptionMessage("foundation.OperationNotAllowed", new String[]{data.getKey()}));
                    }
                    return false;
                }
                return MetaConstants.OPERATION_ADD.equals(data.getOperation());
            }).collect(Collectors.toList());

    updatedCodeList.setData(finalData);
    if (!CollectionUtils.isEmpty(exceptionMessagesList)) {
        throw new EntityValidationException(HTTPClientError.BAD_REQUEST, exceptionMessagesList);
    }
    return updatedCodeList;
}
验证效果

修改后运行测试用例,请求中带DELETE标记的val1、val4会被优先保留并识别为DELETE操作过滤,仅保留存量中未出现在请求中的val3,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:12:03