Skip to content

Instantly share code, notes, and snippets.

@HelgeG
Created October 17, 2017 08:51
Show Gist options
  • Save HelgeG/0c0b14228f75e91b7542bd6979a05b49 to your computer and use it in GitHub Desktop.
Save HelgeG/0c0b14228f75e91b7542bd6979a05b49 to your computer and use it in GitHub Desktop.
Binding for turning Postgres JSONB columns into Jackson JsonNode and vice versa
package com.sqa.virtuoso.webserver.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Types;
import java.util.Objects;
import com.fasterxml.jackson.databind.JsonNode;
import org.jooq.Binding;
import org.jooq.BindingGetResultSetContext;
import org.jooq.BindingGetSQLInputContext;
import org.jooq.BindingGetStatementContext;
import org.jooq.BindingRegisterContext;
import org.jooq.BindingSQLContext;
import org.jooq.BindingSetSQLOutputContext;
import org.jooq.BindingSetStatementContext;
import org.jooq.Converter;
import org.jooq.impl.DSL;
public class JsonNodeBinding implements Binding<Object, JsonNode> {
@Override
public Converter<Object, JsonNode> converter() {
return new Converter<Object, JsonNode>() {
@Override
public JsonNode from(Object fromObject) {
return fromObject == null ? new ObjectMapper().createObjectNode() : parse("" + fromObject);
}
@Override
public Object to(JsonNode jsonNode) {
return jsonNode == null ? null : jsonNode.toString();
}
@Override
public Class<Object> fromType() {
return Object.class;
}
@Override
public Class<JsonNode> toType() {
return JsonNode.class;
}
};
}
@Override
public void sql(final BindingSQLContext<JsonNode> ctx) throws SQLException {
ctx.render().visit(DSL.val(ctx.convert(converter()).value())).sql("::json");
}
@Override
public void register(final BindingRegisterContext<JsonNode> ctx) throws SQLException {
ctx.statement()
.registerOutParameter(ctx.index(),
Types.VARCHAR);
}
@Override
public void set(final BindingSetStatementContext<JsonNode> ctx) throws SQLException {
ctx.statement()
.setString(ctx.index(),
Objects.toString(ctx.convert(converter()).value(),
null));
}
@Override
public void set(final BindingSetSQLOutputContext<JsonNode> ctx) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
@Override
public void get(final BindingGetResultSetContext<JsonNode> ctx) throws SQLException {
ctx.convert(converter()).value(ctx.resultSet().getString(ctx.index()));
}
@Override
public void get(final BindingGetStatementContext<JsonNode> ctx) throws SQLException {
ctx.convert(converter()).value(ctx.statement().getString(ctx.index()));
}
@Override
public void get(final BindingGetSQLInputContext<JsonNode> ctx) throws SQLException {
throw new SQLFeatureNotSupportedException();
}
static JsonNode parse(String src) {
try {
return new ObjectMapper().readValue(src, JsonNode.class);
} catch(Throwable t) {
throw new RuntimeException(t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment