updating object with spring data mongodb and kotlin is not working

∥☆過路亽.° 提交于 2019-11-28 04:37:52

问题


I have the following request handler

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(...)
    }

and the following mongodb reactive repository

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

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?


回答1:


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).

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
}


来源:https://stackoverflow.com/questions/49151066/updating-object-with-spring-data-mongodb-and-kotlin-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!