Search code examples
spring-bootspring-webfluxreactiver2dbc

Springboot Reactive findByusername return "monomap" by r2dbc


I am writing the reactive springboot with mysql and r2dbc.When i writing the query with findByUsername, it just return a String "monotype" instead of an object.

Code:

@Override
    public Mono<UserDetails> findByUsername(String username) {

            log.info("get user");
        System.out.println(userRespository.findByUsername(username));  //print "monoNext" in the console
              Mono<UserDetails> ans=  userRespository.findByUsername(username).switchIfEmpty(Mono.error(new RuntimeException())).map(
                      SecurityUser::new
              );

              return ans;

My respository:

@Repository
public interface UserRespository extends R2dbcRepository<User,Integer> {
    @Query("SELECT * FROM user_info WHERE username = :username ;")
    Mono<User> findByUsername(String username);
}

ANyone have idea for it?


Solution

  • It is because you actually print Mono.toString() because repository returns Mono

    To print User when it is found you should put a callback to your reactive chain, using, for example, doOnNext() operator

    return userRespository.findByUsername(username)
                    // put this callback means "when user is found, print whatever you want here"
                    .doOnNext(user -> System.out.println(user))
                    .switchIfEmpty(Mono.error(new RuntimeException()))
                    .map(SecurityUser::new);