Java 是否可以编写数据类型转换器来处理postgres JSON列?

Java 是否可以编写数据类型转换器来处理postgres JSON列?,java,sql,postgresql,jooq,Java,Sql,Postgresql,Jooq,理想情况下,在Java方面使用Jackson。我尝试了显而易见的解决方案: public class JsonObjectConverter implements Converter<Object, ObjectNode> { private final ObjectMapper mapper = new ObjectMapper(); @Override public ObjectNode from(Object dbo) { try {

理想情况下,在Java方面使用Jackson。我尝试了显而易见的解决方案:

public class JsonObjectConverter implements Converter<Object, ObjectNode> {

    private final ObjectMapper mapper = new ObjectMapper();

    @Override public ObjectNode from(Object dbo) {
        try {
            return dbo != null ? mapper.readValue((String) dbo, ObjectNode.class) : null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override public Object to(ObjectNode uo) {
        try {
            return uo != null ? mapper.writeValueAsString(uo) : null;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override public Class<Object> fromType() {
        return Object.class;
    }

    @Override public Class<ObjectNode> toType() {
        return ObjectNode.class;
    }
}
然而,由于jOOQs强制的类型安全性(顺便说一句,这很好),我不能仅仅添加一个
.cast(String.class)
就可以了。那么,我是否需要在转换器中执行其他操作,或者应该以不同的方式调用代码?我目前正在这样做:

Long id = ...
ObjectNode stuff = ...
create.insertInto(MY_TABLE)
    .set(MY_TABLE.ID, id)
    .set(MY_TABLE.STUFF, stuff)
    .execute();

我在代码中的其他地方使用了可更新的记录。

是的,但您需要使用Postgres特定的API。在上面的代码中,您需要将from/to方法替换为以下方法:

org.jooq.exception.DataAccessException: SQL [insert into "public"."my_table" ("id", "stuff") values (?, ?)]; ERROR: column "stuff" is of type json but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.
@Override
public ObjectNode from(Object databaseObject) {
    if (databaseObject == null) { return null; }
    try {
        PGobject dbo = (PGobject) databaseObject;
        return mapper.readValue(dbo.getValue(), ObjectNode.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
public Object to(ObjectNode userObject) {
    if (userObject == null) { return null; }
    try {
        PGobject dbo = new PGobject();
        dbo.setType("json");
        dbo.setValue(mapper.writeValueAsString(userObject));
        return dbo;
    } catch (JsonProcessingException|SQLException e) {
        throw new RuntimeException(e);
    }
}

仅使用
转换器
可能无法获得100%正确的JSON数据类型。理想情况下,您应该使用jOOQ 3.5实现,如下所述:


可以将代码生成器配置为直接在数据库列上使用自定义的
绑定
(代替或添加到
转换器
)。
绑定将负责JDBC级别上所有必要的交互。

是的,升级到3.5已在我的待办事项列表中。