首页 > 解决方案 > jOOQ 幂等批量插入

问题描述

我正在尝试实现幂等插入,这个查询看起来很适合这个任务

insert into test_table
select *
from (
         values (1, 2, 3, 4),
                (3, 4, 5, 6),
                (1, 2, 3, 4),
                (3, 4, 5, 6)
     ) as data(a, b, c, d)
where not exists(select 1
                 from test_table
                 where test_table.a = data.a
                   and test_table.b = data.b
                   and test_table.c = data.c);

请帮助将此查询转换为 jOOQ DSL
我使用的是 Greenplum 数据库并且不支持ON CONFLICT语法

标签: javasqljooq

解决方案


ctx.insertInto(TEST_TABLE)
   .select(
       select()
       .from(values(
           row(1, 2, 3, 4),
           row(3, 4, 5, 6),
           row(1, 2, 3, 4),
           row(3, 4, 5, 6)
       ).as("data", "a", "b", "c", "d"))
       .whereNotExists(
           selectOne()
           .from(TEST_TABLE)
           .where(TEST_TABLE.A.eq(field(name("data", "a"), TEST_TABLE.A.getDataType())))
           .and(TEST_TABLE.B.eq(field(name("data", "b"), TEST_TABLE.A.getDataType())))
           .and(TEST_TABLE.C.eq(field(name("data", "c"), TEST_TABLE.A.getDataType())))
       )
   )
   .execute();

这个答案是假设您正在使用代码生成器TEST_DATA(否则,请手动构造您的标识符,如上图所示name("data", "a"),等等或如here所示)。此外,它假设:

import static org.jooq.impl.DSL.*;

正式支持 Greenplum 时,请参阅 #4700,然后ON CONFLICTON DUPLICATE KEY IGNORE可以为您模拟。


推荐阅读