首页 > 解决方案 > 将jOOQ的批处理加载器与onDuplicateKeyUpdate一起使用时,如何仅更新某些字段?

问题描述

是否可以仅在找到重复项时使用 jOOQ 的batchAll()加载器更新某些字段?类似于如何onDublicateKeyUpdate()用于单个记录:https ://www.jooq.org/doc/latest/manual/sql-building/sql-statements/insert-statement/insert-on-duplicate-key/ 。

我要更改的代码,仅在存在重复时更新一个字段:

dsl.loadInto(TABLE)
        .batchAll()
        .onDuplicateKeyUpdate()
        .loadRecords(records)
        .fields(TABLE.fields())
        .execute();

标签: javasqlpostgresqljooq

解决方案


Loader不,这对于API是不可能的,但是您可以使用批处理 API以编程方式使用单个语句的普通批处理,或者甚至使用批处理连接,它收集所有 JDBC 语句并延迟执行,直到可以执行批处理:

dsl.batched(c -> {
    for (Record record : records) {
        c.dsl().insertInto(TABLE)
               .set(record)
               .onDuplicateKeyUpdate()
               .set(TABLE.FIELD_OF_INTEREST, record.get(TABLE.FIELD_OF_INTEREST))
               .execute(); // Actual execution is delayed until the end of the lambda
    }
}); // Now, all collected statements are batched together

推荐阅读