微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决从JPA / Hibernate将数组值传递到PostgreSQL

我尝试从JPA / Hibernate环境中将整数数组值传递给plpgsql存储过程。但我总是得到执行: fn_test_array(bytea)函数不存在。

我写了一个简短的演示应用程序,演示了该问题。 (Wildfly AS,JPA / Hibernate,Postgresql 12)

是的,我知道int []。class是垃圾,但是解决方案是什么? :)

存储过程:

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$
;

从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);

例外:

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

预先感谢您的帮助。

解决方法

很遗憾,我没有找到合理的解决方案。但是,我用JDBC连接解决了它。它是这样的。

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();
        }
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。