我需要复制属性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)
之后添加一些内容但到目前为止我所尝试的一切都不起作用。
感谢您的宝贵时间
最佳答案
由于您没有显示 PersonEntity
和 UserEntity
,我们只能猜测它们的属性以及 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/