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

如何使用Optional将Organisation更新方法重构为单行代码?

实现代码

首先你的原有代码存在功能缺陷:查询到已存在的Organisation实体后,没有将传入参数org的业务字段同步到待更新的实体上,直接调用save不会产生任何实际数据变更,属于无效操作。

保留原逻辑(无论是否更新都返回Optional.empty())的写法

public Optional<Organisation> update(Organisation org) {
    return organisationRepository.findById(org.getId())
            .map(existOrg -> {
                // 这里根据你的业务规则做属性拷贝,排除不可更新的字段比如主键、创建时间等
                // 示例用Spring自带的BeanUtils,你也可以替换为项目中用的其他属性映射工具
                org.springframework.beans.BeanUtils.copyProperties(org, existOrg, "id", "createTime");
                return organisationRepository.save(existOrg);
            })
            .flatMap(updated -> Optional.empty());
}

更符合常规业务的写法

通常更新操作会返回更新后的实体供上层逻辑使用,不需要强制返回空的话可以直接去掉最后的flatMap:

public Optional<Organisation> update(Organisation org) {
    return organisationRepository.findById(org.getId())
            .map(existOrg -> {
                org.springframework.beans.BeanUtils.copyProperties(org, existOrg, "id", "createTime");
                return organisationRepository.save(existOrg);
            });
}

极简写法(如果你确实不需要更新字段,仅要触发save操作)

如果你的业务逻辑确实不需要修改实体字段,仅要触发save操作,可以简化为:

public Optional<Organisation> update(Organisation org) {
    return organisationRepository.findById(org.getId())
            .map(organisationRepository::save)
            .flatMap(ignored -> Optional.empty());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:30:01