Jooq dsl 用于批量插入地图、数组等

Jooq dsl for batch insert of maps, arrays and so forth

我希望使用 jooq dsl 对 postgres 进行批量插入。我知道这是可能的,但我在正确设置数据格式方面遇到了问题。

dslContext.loadInto(table).loadJSON(json-data).fields(...).execute();

是我的起点。棘手的部分似乎是将 Map 放入 jsonb 列。

我已根据 this 描述对数据进行了格式化,jooq 似乎还可以。直到 map/json-in-json 出现。

还有一个json数组列也需要处理。

问题:

  1. 这是一个合理的方法吗?
  2. 如果不是 - 您会推荐什么?

我看到错误:

ERROR: column "changes_to" is of type jsonb but expression is of type character varying
Hint: You will need to rewrite or cast the expression.

编辑:

    try (DSLContext context = DSL.using(pgClient.getDataSource(), SQLDialect.POSTGRES_10)) {
        context.loadInto(table(RECORD_TABLE))
                .loadJSON(jsonData)
                .fields(field(name(RECORD_ID_COLUMN)),
                        field(name(OTHER_ID_COLUMN)),
                        field(name(CHANGES_TO_COLUMN)),
                        field(name(TYPE_COLUMN)),
                        IDS_FIELD)
                .execute();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

json 数据:

{"fields":[{"name":"rec_id","type":"VARCHAR"},{"name":"other_id","type":"VARCHAR"},{"name":"changes_to","type":"jsonb"},{"name":"en_type","type":"VARCHAR"},{"name":"ids","type":"BIGINT[]"}],"records":[["recid","crmid","{\"key0\":\"val0\"}","ent type",[10,11,12]],["recid2","crmid2","{\"key0\":\"val0\"}","ent type2",[10,11,12]]]}

问题是如何格式化 'changes_to' 和 'ids' 列。

如果你不使用 jOOQ's code generator (and you should!) jOOQ 不知道你的列是什么数据类型,如果你创建 field(name("...")),所以它不会能够正确绑定你的价值观。当然,Loader API 可以读取 JSON header 信息,但目前还不能。

相反,为什么不只是:

  • 为您的列引用提供明确的类型信息,例如 field(name(CHANGES_TO_COLUMN), SQLDataType.JSONB)
  • 更好:使用代码生成器,在这种情况下,您已经拥有与 Field 表达式关联的所有类型信息。