Search code examples
springkotlinspring-data-r2dbc

How do I map a class using spring data and r2dbc in kotlin


The org.springframework.r2dbc DatabaseClient class has moved to

import org.springframework.r2dbc.core.DatabaseClient;

from

import org.springframework.data.r2dbc.core.DatabaseClient;

The Spring data documentation https://spring.io/projects/spring-data-r2dbc refers to a simple 'as' method to convert to an object

   databaseClient
        .sql("select * from reading")
        .as(CrepsReading::class.java)
        .fetch()
        .all()
        .asFlow()

It doesn't wok. Neither does map(class). Only mapping class seems to work.

     val all: Flux<CrepsReading> = databaseClient
            .sql("SELECT id, name FROM person")
            .map(CrepsReading::class)
            .fetch().all()

How do you map an object with spring-data-r2dbc (1.2.0) simply? Is there documentation that describes the use of the DatabaseClient that is part of spring-data-r2dbc?


Solution

  • In Spring 5.3/Spring Data R2dbc, the DatabaseClient is refactored and moved to the core of Spring framework.

    Check my example to view how to handle the resulting map.

        public static final BiFunction<Row, RowMetadata, Post> MAPPING_FUNCTION = (row, rowMetaData) -> Post.builder()
                .id(row.get("id", UUID.class))
                .title(row.get("title", String.class))
                .content(row.get("content", String.class))
                .status(row.get("status", Post.Status.class))
                .metadata(row.get("metadata", Json.class))
                .createdAt(row.get("created_at", LocalDateTime.class))
                .build();
    
        private final DatabaseClient databaseClient;
    
        public Flux<Post> findByTitleContains(String name) {
            return this.databaseClient
                    .sql("SELECT * FROM posts WHERE title LIKE :title")
                    .bind("title", "%" + name + "%")
                    .map(MAPPING_FUNCTION)
                    .all();
        }