如何使用JOOQ Query Builder使用使用常量值的select语句构建Insert into

时间:2018-08-30 20:12:13

标签: java postgresql jooq

我有一个插入语句,该语句正在插入一些常量值,并且需要通过查找从其他表中选择一些引用键。查询看起来像这样。

s), then one of the two models is defined first. This means that if you define

我的JOOQ查询生成器代码如下

first, it can not refer to the

此语句无法编译,并出现以下错误

Insert into repository.buffer (
    b_external_id,
    b_buffer_type_id,
    b_entrypoints,
    b_site_id,
    b_state,
    b_uri)
select '100A',bt_id,'["/locations/100A"]'::jsonb,s_id,'ready','/buffers/100A'
from  repository.site, repository.buffer_type
where s_name = 'bar'
and bt_external_id = 'FOO';

我以某种方式在选择的选择返回类型中使用内联时,将选择更改为SelectConditionStep而不是Select。

有解决这个问题的线索吗?

1 个答案:

答案 0 :(得分:1)

编译器推断SelectConditionStep的事实在这里无关紧要,因为它是Select的子类型,因此INSERT .. SELECT语句完全可以接受。问题在于,当在您的insertInto()子句中使用普通SQL并且不提供任何列数据类型时,编译器将为每个单独的列而不是Object推断出String

请记住,jOOQ是一种非常强类型的API,这主要可以帮助您正确使用SQL。在特定情况下,请确保您将在每个列引用上指定一种数据类型:

dslContext
    .insertInto(
        table("repository.buffer"),
        field("b_external_id", String.class), // Change here
        field("b_buffer_type_id"),
        field("b_entrypoints", Object.class), // Change here
        field("b_site_id"),
        field("b_state", String.class), // Change here
        field("b_uri", String.class)) // Change here
    .select(select(
            inline(null, String.class),
            field("bt_id"),
            inline(null, Object.class),
            field("s_id"),
            inline(null, String.class),
            inline(null, String.class))
            .from(table("repository.site"), table("repository.buffer_type"))
            .where(field("s_name").eq(cast(null, String.class)))
            .and(field("bt_external_id").eq(cast(null, Integer.class))))
        .onConflict().doNothing()
    .getSQL();

甚至更好的是,使用代码生成器,在这种情况下,所有这些都将自动为您完成,从而提高了可读性。

相关问题