Is it possible to write a data type Converter to handle postgres JSON columns?

戏子无情 提交于 2019-12-04 16:36:49
Lukas Eder

You probably won't get the JSON data type 100% correct with a Converter only. Ideally, you should use a jOOQ 3.5 org.jooq.Binding implementation, which is documented here:

The code generator can be configured to use your custom Binding (instead or in addition to Converters) directly on your database columns. The Binding will then take care of all necessary interaction on a JDBC level.

Yes, it is, but you need to use Postgres specific API. In the code above you need to replace the from/to methods with the following:

@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);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!