java - 使用 Spring WebFlux 为 Mono<Entity> 添加值

标签 java spring mapping spring-webflux

我需要复制属性Friends (这是一个 ArrayList)来自 Mono<PersonEntity>Mono<UserEntity> (数据库中没有 Friends 属性),但我找不到正确的方法,所以当我映射 Mono<UserEntity> 时到Dto,现场Friends结果是一个空数组[]。

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label).flatMap(person -> {
         return UserRepository.findByID(id);     
    })
            .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
            .map(this::mapper);
}

我想我应该在 findById(id) 之后添加一些内容但到目前为止我所尝试的一切都不起作用。 感谢您的宝贵时间

最佳答案

由于您没有显示 PersonEntityUserEntity,我们只能猜测它们的属性以及 getter 和 setter 方法。尽管如此,以下几行应该有效:

public Mono<Dto> findEntityByIdAndLabel(Long id, String label) {
    return getPersonByIdAndLabel(id, label)
        .zipWith(UserRepository.findByID(id))
        .map(tuple -> {
            List friends = tuple.getT1().getFriends();
            UserEntity user = tuple.getT2():
            user.setFriends(friends);
            return user;
        })
        .switchIfEmpty(Mono.error(new EntityNotFoundException(entity.toString(), id.toString(), label)))
        .map(this::mapper);
}

重要的是 zipWith,它将 Mono 和另一个 Mono 的结果组合成 Tuple2然后您就可以轻松绘制 map 。您可以在reference documentation中阅读更多相关信息。 .

关于java - 使用 Spring WebFlux 为 Mono<Entity> 添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70094683/

相关文章:

java - 按网格顺序排列三角形

spring - JSP EL div 运算符 - 奇怪的行为

spring - Spring Boot与MySQL中的多个架构连接

java - Hibernate - 外键而不是实体

java - 对象作为 java 8 中树状图中的键

java - 错误: constructor for a xyz class is not defined

java - 实现 Spring Web 服务的更好方法

arrays - 将 Range 直接映射到 Array

java - Jackson:反序列化列表时捕获单个项目的异常

java - 在 Java 中设置 GUI 窗口焦点在行上