![](/img/trans.png)
[英]Spring webflux convert Entity class to Mono DTO object
[英]Add value to a Mono<Entity> with Spring WebFlux
我需要將屬性Friends
(這是一個 ArrayList)從Mono<PersonEntity>
到Mono<UserEntity>
(在數據庫中沒有Friends
屬性),但我找不到正確的方法,所以當我 map 將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。 您可以在參考文檔中閱讀更多相關信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.