Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - updating object with spring data mongodb and kotlin is not working

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...