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

Spring WebFlux中Mono<PersonEntity>属性拷贝到Mono<UserEntity>方案咨询

问题根因

原有逻辑中flatMap操作拿到PersonEntity后直接返回数据库查询的UserEntity结果,直接丢弃了携带Friends属性的PersonEntity对象,后续映射Dto时自然无法读取到Friends值。

可行解决方案

方案1:直接为UserEntity注入Friends属性

适用于UserEntity类已定义Friends字段、仅数据库表未存储该字段的场景:

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label)
            .flatMap(person -> UserRepository.findByID(id)
                    // 拿到数据库返回的UserEntity后注入Friends属性
                    .map(user -> {
                        // 做非空判断避免空指针,无Friends数据时默认赋值空集合
                        user.setFriends(Optional.ofNullable(person.getFriends()).orElse(new ArrayList<>()));
                        return user;
                    })
            )
            .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
            .map(this::mapper);
}

方案2:映射Dto时直接传入Friends属性

适用于不想修改UserEntity结构的场景,需要对应调整mapper方法增加Friends入参,直接将属性写入Dto:

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label)
            // 把PersonEntity和UserEntity打包向下传递
            .flatMap(person -> Mono.zip(Mono.just(person), UserRepository.findByID(id)))
            .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
            // 调用重载的mapper方法同时传入UserEntity和Friends属性
            .map(tuple -> mapper(tuple.getT2(), Optional.ofNullable(tuple.getT1().getFriends()).orElse(new ArrayList<>())));
}

对应的mapper重载方法示例:

private Dto mapper(UserEntity user, List<Friend> friends) {
    Dto dto = mapper(user); // 复用原有单参mapper逻辑
    dto.setFriends(friends);
    return dto;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:24:00