0

我的任务是通过 r2dbc 数据库客户端插入实体,并将结果(映射)转换为实体。我想这样做:

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

但问题是转换器实体MappingR2dbcConverter不是由 spring 创建的。所以,我决定自己创建它:

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

我的问题,将结果映射转换为实体是否正确?

4

1 回答 1

0

R2dbc DatabaseClient 将成为 Spring 框架 5.3 的一部分,请参阅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();
    }
于 2020-09-13T12:57:50.480 回答