Spring R2DBC repository.save() 无法在 flatMap() 中工作

问题描述 投票:0回答:1

以下是写在服务中的函数。

public Mono<BrandRest> createBrand(CreateBrandRequest request) {
        record BrandCategoryRest(Brand brandRest, List<CategoryRest> categoryRests){}

        return Flux.fromIterable(request.categories())
                .flatMap(category -> categoryClient.findByName(category)
                        .next())
                .collectList()
                .flatMap(categoryRests -> {
                    var brand = new Brand();
                    brand.setBrandName(request.brandName());
                    brand.setStatus(true);
                    brand.setDescription(request.description());
                    brand.setImageUrl(request.imageUrl());
                    brand.setNoOfProducts(0L);
                    return brandRepository.save(brand)
                            .flatMap(b -> {
                                for (CategoryRest categoryRest: categoryRests) {
                                    var brandCategory = new BrandCategory(b.getBrandId(), categoryRest.categoryId());
                                    brandCategoryRepository.save(brandCategory);
                                }
                                return Mono.just(new BrandCategoryRest(b, categoryRests));
                            });
                })
                .map(brandCategoryRest -> BrandRest.of(brandCategoryRest.brandRest(), brandCategoryRest.categoryRests()));

    }

在此,brandRepository.save(brand) 工作正常并将实体保存在数据库中。但 brandCategoryRepository.save(brandCategory) 未在数据库中保存任何记录。

我使用 postgresql 作为数据库。

spring spring-webflux r2dbc
1个回答
0
投票

我认为以下代码在

flatMap
中不起作用。

for (CategoryRest categoryRest: categoryRests) {
    var brandCategory = new BrandCategory(b.getBrandId(), categoryRest.categoryId());
    brandCategoryRepository.save(brandCategory);
}

可以这样改。

.flatMap(b -> {
    //make the input arg is a List or Flux
   return brandCategoryRepository.saveAll(brandCategories)
       .then(Mono.just(....))
   }
)
© www.soinside.com 2019 - 2024. All rights reserved.