voipp
voipp

Reputation: 1461

How to convert databaseClient result into object?

I have a task to insert entity through r2dbc database client, and convert the result (map) into the entity. I want to do it this way:

databaseClient.insert().into(ApplicationData.class)
            .using(applicationData)
            .map(converter.populateIdIfNecessary(applicationData))
            .first();

But the problem is converter entity MappingR2dbcConverter isn't created by spring. So, I decided to create it myself:

@Bean
public MappingR2dbcConverter converter(RelationalMappingContext mappingContext,
                                                             R2dbcCustomConversions r2dbcCustomConversions)....

My question, is it correct way to convert result map into entity?

Upvotes: 0

Views: 1234

Answers (1)

Hantsy
Hantsy

Reputation: 9321

R2dbc DatabaseClient will be part of Spring framework 5.3, see My example for Spring 5.3 M2.

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();

public Flux<Post> findAll() {
        return this.databaseClient
                .sql("SELECT * FROM posts")
                .filter((statement, executeFunction) -> statement.fetchSize(10).execute())
                .map(MAPPING_FUNCTION)
                .all();
    }

    public Mono<Post> findById(UUID id) {
        return this.databaseClient
                .sql("SELECT * FROM posts WHERE id=:id")
                .bind("id", id)
                .map(MAPPING_FUNCTION)
                .one();
    }

Upvotes: 1

Related Questions