从jOOQ 3.5开始,您可以将自己的自定义数据类型绑定注册到代码生成器,如此处所述:
http://www.jooq.org/doc/latest/manual/pre-generation/custom-data-type-
bindings
与不同
Converter,a
Binding指示如何在jOOQ内的JDBC级别上处理数据类型,而jOOQ不知道您的实现。即,不仅可以定义如何在
<T>和
<U>类型之间进行转换(
T=数据库类型,
U=用户类型),而且还可以定义这些类型的方式:
- 呈现为SQL
- 绑定到PreparedStatement
- 绑定到SQLOutput
- 在CallableStatements中注册为OUT参数
- 从结果集中获取
- 从SQLInput获取
- 从CallableStatements获取作为OUT参数
这里提供
Binding了与Jackson一起使用以产生
JsonNode类型的示例:
public class PostgresJSonJacksonJsonNodeBinding implements Binding<Object, JsonNode> { @Override public Converter<Object, JsonNode> converter() { return new PostgresJSonJacksonJsonNodeConverter(); } @Override public void sql(BindingSQLContext<JsonNode> ctx) throws SQLException { // This ::json cast is explicitly needed by PostgreSQL: ctx.render().visit(DSL.val(ctx.convert(converter()).value())).sql("::json"); } @Override public void register(BindingRegisterContext<JsonNode> ctx) throws SQLException { ctx.statement().registerOutParameter(ctx.index(), Types.VARCHAR); } @Override public void set(BindingSetStatementContext<JsonNode> ctx) throws SQLException { ctx.statement().setString( ctx.index(), Objects.toString(ctx.convert(converter()).value())); } @Override public void get(BindingGetResultSetContext<JsonNode> ctx) throws SQLException { ctx.convert(converter()).value(ctx.resultSet().getString(ctx.index())); } @Override public void get(BindingGetStatementContext<JsonNode> ctx) throws SQLException { ctx.convert(converter()).value(ctx.statement().getString(ctx.index())); } // The below methods aren't needed in PostgreSQL: @Override public void set(BindingSetSQLOutputContext<JsonNode> ctx) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public void get(BindingGetSQLInputContext<JsonNode> ctx) throws SQLException { throw new SQLFeatureNotSupportedException(); }}而
Converter这是上面使用可以在这里看到:
public class PostgresJSonJacksonJsonNodeConverter implements Converter<Object, JsonNode> { @Override public JsonNode from(Object t) { try { return t == null ? NullNode.instance : new ObjectMapper().readTree(t + ""); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Object to(JsonNode u) { try { return u == null || u.equals(NullNode.instance) ? null : new ObjectMapper().writevalueAsString(u); } catch (IOException e) { throw new RuntimeException(e); } } @Override public Class<Object> fromType() { return Object.class; } @Override public Class<JsonNode> toType() { return JsonNode.class; }}您现在可以通过代码生成器配置注册上述绑定:
<customType> <name>com.example.PostgresJSONJacksonJsonNodeBinding</name> <type>com.fasterxml.jackson.databind.JsonNode</type> <binding>com.example.PostgresJSONJacksonJsonNodeBinding</binding></customType><forcedType> <name>com.example.PostgresJSONJacksonJsonNodeBinding</name> <expression>my_schema.table.json_field</expression></forcedType>



