使用JOOQ将数据插入Postgres中的JSON列

时间:2019-06-04 10:38:53

标签: json postgresql java-8 jooq

我有一个Postgres数据库,可以使用JOOQ对其进行读写。我的一个数据库表中有一列类型为JSON。当我尝试使用以下查询将数据插入此列时,出现错误

Exception in thread "main" org.jooq.exception.DataAccessException: SQL [update "public"."asset_state" set "sites_as_json" = ?]; ERROR: column "sites_as_json" is of type json but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

下面是用于将数据插入列中的代码

SiteObj s1 = new SiteObj();
s1.setId("1");
s1.setName("Site1");
s1.setGeofenceType("Customer Site");

SiteObj s2 = new SiteObj();
s2.setId("2");
s2.setName("Site2");
s2.setGeofenceType("Customer Site");

List<SiteObj> sitesList = Arrays.asList(s1, s2);
int result = this.dsl.update(as).set(as.SITES_AS_JSON, LambdaUtil.convertJsonToStr(sitesList)).execute();

调用LambdaUtil.convertJsonToStr(sitesList)输出一个看起来像这样的字符串...

[{"id":"1","name":"Site1","geofenceType":"Customer Site"},{"id":"2","name":"Site2","geofenceType":"Customer Site"}]

要插入JSON列,我需要做什么?

1 个答案:

答案 0 :(得分:1)

为了让jOOQ正确地将JSON字符串绑定到JDBC驱动程序,您将需要实现一个数据类型绑定,如下所示:

https://www.jooq.org/doc/latest/manual/code-generation/custom-data-type-bindings

重要的一点是您生成的SQL需要产生显式的类型转换,例如:

@Override
public void sql(BindingSQLContext<JsonElement> ctx) throws SQLException {
    // Depending on how you generate your SQL, you may need to explicitly distinguish
    // between jOOQ generating bind variables or inlined literals.
    if (ctx.render().paramType() == ParamType.INLINED)
        ctx.render().visit(DSL.inline(ctx.convert(converter()).value())).sql("::json");
    else
        ctx.render().sql("?::json");
}