简体   繁体   English

将数组值从 JPA/Hibernate 传递给 PostgreSQL

[英]Pass array values to PostgreSQL from JPA/Hibernate

I try pass integer array value a plpgsql stored procedure from JPA/Hibernate enviroment.我尝试从 JPA/Hibernate 环境传递整数数组值一个 plpgsql 存储过程。 But I always get an execpetion: function fn_test_array(bytea) does not exist.但我总是得到一个执行:函数 fn_test_array(bytea) 不存在。

I wrote a short demo application, which demonstrates the problem.我写了一个简短的演示应用程序,它演示了这个问题。 (Wildfly AS, JPA/Hibernate, PostgreSQL 12) (Wildfly AS、JPA/Hibernate、PostgreSQL 12)

Yes, I know, the int[].class is a rubbish, but then what is the solution?是的,我知道, int[].class 是垃圾,但解决方案是什么? :) :)

Stored procedure:存储过程:

CREATE OR REPLACE FUNCTION public.fn_test_array(in_arr integer[], OUT res_int bigint)
RETURNS bigint
LANGUAGE plpgsql
AS $function$
BEGIN

res_int := 201;
 
END;
$function$
;

Call from java:从 Java 调用:

StoredProcedureQuery query2 = em.createStoredProcedureQuery("fn_test_array")
.registerStoredProcedureParameter("in_arr", int[].class, ParameterMode.IN)
.registerStoredProcedureParameter("res_int", Long.class, ParameterMode.OUT)
.setParameter("in_arr", new int[]{1, 2});

query2.execute();
Long res2 = (Long) query2.getOutputParameterValue("res_int");
System.out.println("res2: " + res2);

Exception:例外:

11:26:11,933 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-19) SQL Error: 0, SQLState: 42883
11:26:11,933 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-19) ERROR: function fn_test_array(bytea) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 15

Thank you in advance for your help.预先感谢您的帮助。

Unfortunately I not found sophistical solution.不幸的是,我没有找到巧妙的解决方案。 However, I soled it with JDBC connection.但是,我使用 JDBC 连接解决了它。 It works like this.它是这样工作的。

final Session session = em.unwrap(Session.class);  //Hibernate session
session.doWork(new Work() {
    @Override
    public void execute(Connection connection) throws SQLException {
        try {
            String query = "{CALL fn_test_array(?, ?)}";
            CallableStatement stmt = connection.prepareCall(query);
            
            Integer[] numbers = {1, 2, 3, 5};
            final Array in_arr = connection.createArrayOf("integer", numbers);            
            stmt.setArray(1, in_arr);            
            stmt.registerOutParameter(2, Types.BIGINT);
            stmt.execute();

            Long resLong = stmt.getLong(2);
            System.out.println("resLong: " + resLong);
            stmt.close();            
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM