【问题标题】:R2dbc custom converterR2dbc 自定义转换器
【发布时间】:2021-01-28 17:51:02
【问题描述】:

如何将我的自定义转换器添加到 mu spring boot 应用程序? 我的实体字段

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

我的转换器是

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

我有一个例外

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]
........

我该如何解决,请帮助我!

【问题讨论】:

    标签: spring-data-r2dbc r2dbc r2dbc-postgresql


    【解决方案1】:

    您需要向 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);
    }
    

    您不需要覆盖整个 R2dbcConfiguration。

    【讨论】:

    • 是的,行得通。在新版本的 r2dbc 构造函数 R2dbcCustomerConversions(converters) 已被弃用,所以从现在开始我们应该使用: R2dbcCustomConversions.of(SqlServerDialect.INSTANCE, converters) 你需要为你的数据库选择正确的方言
    • 我不是 100% 确定他们为什么要强制实施者指定方言。事情变得越来越复杂。
    • 它有效,只需记住一件事:BlockHound 将此转换器视为阻塞。
    • @Moler 此代码中没有任何阻塞。当然,您还需要转换器本身的非阻塞实现。您应该发布一个单独的问题以及您的阻止详细信息。
    • 这应该被标记为正确答案。完美无缺!
    【解决方案2】:

    尝试分别创建ReadingConverterWritingConverter,并在Config文件中注册。

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

    查看完整代码here

    对于 Spring Boot 应用程序,请尝试override the default beans

    【讨论】:

    • 有没有办法不覆盖连接工厂?
    猜你喜欢
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2013-04-12
    • 2016-04-19
    • 2012-03-15
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    相关资源
    最近更新 更多