使用Spring数据MongoDB和Kotlin更新对象不起作用 [英] updating object with spring data mongodb and kotlin is not working

查看:156
本文介绍了使用Spring数据MongoDB和Kotlin更新对象不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下请求处理程序

fun x(req: ServerRequest) = req.toMono()
    .flatMap {
        ...
        val oldest = myRepository.findOldest(...) // this is the object I want to modify
        ...
        val v= anotherMongoReactiveRepository.save(Y(...)) // this saves successfully
        myRepository.save(oldest.copy(
                remaining = (oldest.remaining - 1)
        )) // this is not saved
        ok().body(...)
    }

和以下mongodb反应式存储库

and the following mongodb reactive repository

@Repository
interface MyRepository : ReactiveMongoRepository<X, String>, ... {
}

问题在于,执行save()方法后,对象中没有任何更改.我设法解决了save().block()的问题,但是我不知道为什么在其他存储库中进行的第一次保存有效,而为什么没有.为什么需要block()?

The problem is that after the save() method is executed there is no changed in the object. I managed to fix the problem with save().block() but I don't know why the first save on the other repository works and this one isn't. Why is this block() required?

推荐答案

只有在有人订阅了反应性Publisher之前,什么都不会发生.这就是为什么当您使用block()时它开始起作用的原因.如果您需要调用数据库并在另一个数据库请求中使用结果,而不是使用诸如map(),flatMap()等Mono/Flux运算符...来构建所需的所有操作的管道,然后返回结果Mono/Flux作为控制器的响应. Spring将订阅该Mono/Flux并返回请求.您不需要阻止它.并且不建议这样做(使用block()方法).

Nothing happens until someone subscribes to reactive Publisher. That's why it started to work when you used block(). If you need to make a call to DB and use the result in another DB request than use Mono / Flux operators like map(), flatMap(),... to build a pipeline of all the operations you need and after that return resulting Mono / Flux as controller’s response. Spring will subscribe to that Mono / Flux and will return the request. You don't need to block it. And it is not recommended to do it (to use block() method).

如何在Java中使用MongoDB反应式存储库的简短示例:

Short example how to work with MongoDB reactive repositories in Java:

@GetMapping("/users")
public Mono<User> getPopulation() {
    return userRepository.findOldest()
            .flatMap(user -> {              // process the response from DB
                user.setTheOldest(true);
                return userRepository.save(user);
            })
            .map(user -> {...}); // another processing
}

这篇关于使用Spring数据MongoDB和Kotlin更新对象不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆