【问题标题】:jOOQ - execute postgres user defined function with refcursorjOOQ - 使用 refcursor 执行 postgres 用户定义的函数
【发布时间】:2018-06-06 20:02:41
【问题描述】:

我在执行在 jooq 中接受并返回 postgres refcursor 的函数时遇到了一些问题。我不知道如何实例化ref,即Result<Record>,以及如何遍历我应该从我想要执行的函数中获得的记录。

假设我在 postgres (postgres 9.5) 中有以下函数:

create or replace function foo_cursor(name character varying, ref refcursor)
returns refcursor
as $func$
begin
  open ref for
    select id, first_name, last_name
    from students
    where first_name = name;
  return ref;
end
$func$ 
language plpgsql;

在 postgres 中我是这样执行的:

begin;
select foo_cursor('Konrad', 'my_cursor');
fetch all in "my_cursor";
commit;

函数必须保持不变 - 它返回 refcursor 并接受 refcursor

我想在 jOOQ 中执行它:

Routines.fooCursor(configuration, "Konrad", ____);

但我不知道在____ 中放什么,它需要Result<Record>。我试过类似的东西:

Result<Record> records = DSL.using(configuration).newResult();

但它也没有工作。

【问题讨论】:

    标签: java postgresql jooq


    【解决方案1】:

    jOOQ 在 PostgreSQL 中支持 refcursor 结果类型(或 OUT 参数),但不支持 IN 参数类型,这确实有点怪癖,因为它伪装成一个伪类型标识符。如果你可以将你的函数重载到这个:

    create or replace function foo_cursor(name character varying)
    returns refcursor
    as $func$
    declare
      ref refcursor;
    begin
      open ref for
        select id, first_name, last_name
        from students
        where first_name = name;
      return ref;
    end
    $func$ 
    language plpgsql;
    

    然后,jOOQ 就可以调用该函数了。不需要 jOOQ(或者您,在使用 jOOQ 时)来定义生成的游标名称。

    但是,您可能需要在事务内部运行函数调用。

    【讨论】:

    • 感谢您的回复。我检查过了,但是当我使用Routines.fooCursor(configuration) 时,它给了我DataAccessException 和消息org.postgresql.util.PSQLException: ERROR: cursor "&lt;unnamed portal 1&gt;" does not exist。我试图用declare ref refcursor := 'mycursor'; 实例化refcursor,但是我会得到同样的错误,告诉我mycursor 不存在。
    • @kodi1911:您是否在事务中运行您的 jOOQ 代码?
    • context.transactionResult(config -&gt; Routines.fooCursor(config).getValues("first_name", String.class)); 中运行它就可以了。谢谢您的帮助。你太棒了:)
    • 确实,我依稀记得事务是从 JDBC 客户端调用 refcursor 函数时的一项要求...感谢您的好话 :)
    猜你喜欢
    • 2017-01-09
    • 2018-06-29
    • 2014-06-06
    • 2015-07-12
    • 2019-08-27
    • 2023-04-10
    • 1970-01-01
    • 2017-01-24
    • 2017-01-08
    相关资源
    最近更新 更多