Spring R2DBC中flatMap内的brandCategoryRepository.save()无法生效
问题原因及解决方案
你的代码里brandCategoryRepository.save(brandCategory)无法写入数据库,核心问题是响应式操作未被触发执行:
在Spring WebFlux的Reactor框架中,所有返回Mono/Flux的操作都是惰性的——只有当这些操作被纳入响应式流的订阅链条时,才会实际执行数据库写入。你当前在for循环里直接调用save(),但没有把这些Mono<BrandCategory>对象整合到主流程中,相当于只是定义了操作,但从未触发它运行。
修复后的代码
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 -> { // 将批量保存操作纳入响应式流,确保触发执行 return Flux.fromIterable(categoryRests) .map(categoryRest -> new BrandCategory(b.getBrandId(), categoryRest.categoryId())) .flatMap(brandCategoryRepository::save) .collectList() .then(Mono.just(new BrandCategoryRest(b, categoryRests))); }); }) .map(brandCategoryRest -> BrandRest.of(brandCategoryRest.brandRest(), brandCategoryRest.categoryRests())); }
关键改动说明
- 替换for循环为
Flux.fromIterable(categoryRests),将每个分类转换为BrandCategory对象并纳入流中 - 通过
flatMap(brandCategoryRepository::save)把每个保存操作整合到主响应式链条里 - 用
collectList()等待所有BrandCategory的保存操作完成,再继续后续流程 - 借助
then()方法在批量保存完成后,返回封装好的BrandCategoryRest对象
这样所有数据库操作都会被正确触发,BrandCategory记录就能正常写入PostgreSQL数据库了。
内容的提问来源于stack exchange,提问作者Naveen Kumar
相关产品推荐
相关产品推荐

