【问题标题】:Insert data into JSON column in postgres using JOOQ使用 JOOQ 将数据插入 postgres 中的 JSON 列
【发布时间】:2019-10-19 21:16:16
【问题描述】:

我有一个使用 JOOQ 读/写的 postgres 数据库。我的一个数据库表有一个 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 列?

【问题讨论】:

  • 对于其他想知道如何实现 LambdaUtil.convertJsonToStr 功能的人 - 您可以使用 Jackson 或 GS​​ON 包,例如 herehere

标签: json postgresql java-8 jooq


【解决方案1】:

当前的 jOOQ 版本

jOOQ 原生支持 JSONJSONB 数据类型。您不需要做任何自定义的事情。

历史答案

为了让 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");
}

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2014-08-17
    • 2016-01-31
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2023-03-21
    • 2020-10-05
    相关资源
    最近更新 更多