使用 JDBI 映射 @Json 属性

Tin*_* Ng 6 jdbi jdbi3 jdbi3-core

根据 JDBI 文档https://jdbi.org/#_jackson_2,似乎拥有对象模型的 json 属性非常简单,但是我尝试了以下方法,但遇到了很多问题。

DB:列类型为 Jsonb 的 Postgres

class Event {
    private String name;
    @Json
    private EventProperty jsonProperty;
    ...
}
Run Code Online (Sandbox Code Playgroud)

数据源已配置为

    @Bean
    public Jdbi jdbi(TransactionAwareDataSourceProxy eventStoreTxAwareDataSourceProxy) {
        Jdbi jdbi = Jdbi.create(eventStoreTxAwareDataSourceProxy);
        jdbi.installPlugin(new PostgresPlugin());
        jdbi.installPlugin(new Jackson2Plugin());
    }
Run Code Online (Sandbox Code Playgroud)

SQL用于绑定插入列表

INSERT INTO event (name, json_property)
VALUES (
        :name,
        :jsonProperty)
Run Code Online (Sandbox Code Playgroud)

运行插入代码时,出现以下错误:

org.jdbi.v3.core.statement.UnableToCreateStatementException: no argument factory for type com.EventProperty [statement:"INSERT INTO event (...]
Run Code Online (Sandbox Code Playgroud)

如果我创建了 EventPropertyArgumentFactory 并使用 Jackson ObjectMapper 和 writeValueAsString 那么我可以将其保存到数据库。但是,当从数据库检索它时

 try (Handle handle = jdbi.open()) {
    EventDao dao = handle.attach(EventDao.class);
    return dao.findByName(name);
}
Run Code Online (Sandbox Code Playgroud)

抛出以下错误

java.lang.ClassCastException: Cannot cast org.postgresql.util.PGobject to com.EventProperty
Run Code Online (Sandbox Code Playgroud)

我以为我需要做的就是声明用 @Json 注释的字段,DB 列必须是 json/jsonb 类型并安装插件,但似乎情况并非如此?

有人已经成功尝试过此操作,而无需定义自定义行映射器和参数工厂实现吗?

谢谢

小智 -1

不确定你现在是否已经解决了这个问题,但我刚刚遇到了同样的问题并最终解决了。

基本上,您只需在类的 getter 或 setter 上添加注释,而不是在顶级字段上添加注释。

class Event {
    private String name;
    private EventProperty jsonProperty;
    ...

    @Json
    public getEventProperty() {
        return jsonProperty;
    }
}
Run Code Online (Sandbox Code Playgroud)