Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R2dbc custom converter

How can I add my custom converter to mu spring boot application? My entity field

    @CreatedDate
    @Column(value = "create_time")
    private Instant createTime;

My converters are

    @Bean
    public Converter<Long, Instant> longInstantConverter() {
        return new Converter<Long, Instant>() {
            @Override
            public Instant convert(Long source) {
                return Instant.ofEpochMilli(source);
            }
        };
    }

    @Bean
    public Converter<Instant, Long> instantLongConverter() {
        return new Converter<Instant, Long>() {
            @Override
            public Long convert(@NotNull Instant source) {
                return source.toEpochMilli();
            }
        };
    }

I have an exception

org.springframework.data.mapping.MappingException: Could not read property @org.springframework.data.relational.core.mapping.Column(value=create_time) @org.springframework.data.annotation.CreatedDate()private java.time.Instant com.example.database.model.MyTable.createTime from result set!
.........
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.Long] to type [java.time.Instant]
........

How can I fix it, please help me!

like image 503
Vurtatoo Avatar asked Jan 25 '23 16:01

Vurtatoo


2 Answers

You need to register the converters with R2DBC:

@Bean
public R2dbcCustomConversions customConversions() {
    List<Converter<?, ?>> converters = new ArrayList<>();
    converters.add(new SomeReadConverter());
    converters.add(new SomeWriteConverter());
    return R2dbcCustomConversions.of(MySqlDialect.INSTANCE, converters);
    // deprecated: return new R2dbcCustomConversions(converters);
}

You don't need to override the whole R2dbcConfiguration.

like image 138
Tires Avatar answered Feb 16 '23 11:02

Tires


Try to create ReadingConverter and WritingConverter respectively, and register them in the Config file.

public class DatabaseConfig extends AbstractR2dbcConfiguration {
    //...
    
    @Override
    protected List<Object> getCustomConverters() {
        return List.of(
                new PostReadingConverter(),
                new PostStatusWritingConverter()
        );
    }
}

Check the complete codes here.

For Spring Boot applications, try to override the default beans, or create a R2dbcCustomConversions.

@Bean
public R2dbcCustomConversions r2dbcCustomConversions(ConnectionFactory connectionFactory, ObjectMapper objectMapper) {
    var dialect = DialectResolver.getDialect(connectionFactory);
    var converters = List.of(
               ...
    );
    return R2dbcCustomConversions.of(dialect, converters);
}
like image 36
Hantsy Avatar answered Feb 16 '23 11:02

Hantsy