Reputation: 13
What is the correct way for collecting the value from the Mono object? I have an entity called Student which has both user and student id values.
Mono<Student> student = studentRepository.findStudentByUserid(id);
and I want to use studentId (student.getStudentId()
) to save a new value in different table
StudentSubject ss;
ss.setStudentId(student.getStudentId());
studentsubjectRepository.save(ss);
What is the best approach?
Upvotes: 1
Views: 695
Reputation: 59211
Your question lacks a bit of details, so I'll assume some things from this point.
Let's say your app is using this code:
Mono<StudentSubject> studentSubject = studentRepository.findStudentByUserid(id)
.flatMap(student -> {
StudentSubject subject = new StudentSubject();
subject.setStudentId(student.getStudentId());
return studentsubjectRepository.save(subject);
});
Using the flatMap
operator allows you to chain calls in reactive fashion.
Several things can happen here:
Mono
. The subscription part usually happens in Spring WebFlux so you just need to return that Mono
from your controller method.Mono.empty()
. In this case, your flatMap
operator won't be called and an empty publisher is effectively returned; no StudentSubject
is created. Depending on the expected behavior of your app, you could look into defaultIfEmpty
or switchIfEmpty
operators to deal with that caseonError*
operators.If you're new to Reactor, you can always add a log()
operator wherever you want in the chain (as a regular operator) and you'll see in the logs what happens precisely.
Upvotes: 2