Vurtatoo
Vurtatoo

Reputation: 366

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 this error?

Upvotes: 8

Views: 13129

Answers (2)

Tires
Tires

Reputation: 1602

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.

Upvotes: 12

Hantsy
Hantsy

Reputation: 9241

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

Upvotes: 4

Related Questions