简体   繁体   English

如何使用 Hibernate 调用 PostgreSQL 存储过程

[英]How to call a PostgreSQL stored procedure with Hibernate

I want to create a Stored Procedure in PostgreSQL to make some calculation and return it to My java call.我想在 PostgreSQL 中创建一个存储过程来进行一些计算并将其返回给我的 java 调用。 I have tried Most of the option from Java-Hibernate but not able to succeed.我已经尝试了 Java-Hibernate 中的大多数选项,但未能成功。 Below is my SP.下面是我的SP。

CREATE OR REPLACE FUNCTION "GET_REPORT"()
RETURNS refcursor AS
$BODY$DECLARE
      ref refcursor; 
BEGIN
OPEN ref FOR Select sum(balance),avg(balance) from sales;
RETURN ref;
END$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION "GET_REPORT"()
OWNER TO postgres;

In Java How to call this procedure to get the values.在 Java 中如何调用此过程来获取值。 NOTE: I'm not using hibernate XML files to call quires.注意:我没有使用休眠 XML 文件来调用查询。

Please provide Java code(using Session) and any changes in procedure (if required).请提供 Java 代码(使用 Session)和过程中的任何更改(如果需要)。

You can use JPA StoredProcedureQuery for calling PostgreSQL stored procedures or functions您可以使用 JPA StoredProcedureQuery来调用 PostgreSQL 存储过程或函数

StoredProcedureQuery query = entityManager
    .createStoredProcedureQuery("count_comments")
    .registerStoredProcedureParameter("postId", 
        Long.class, ParameterMode.IN)
    .registerStoredProcedureParameter("commentCount", 
        Long.class, ParameterMode.OUT)
    .setParameter("postId", 1L);
 
query.execute();
 
Long commentCount = (Long) query
    .getOutputParameterValue("commentCount");

Or, if you want to use the Hibernate Session :或者,如果你想使用 Hibernate Session

ProcedureCall call = session
    .createStoredProcedureCall("post_comments");
 
call.registerParameter(1, 
    void.class, ParameterMode.REF_CURSOR);
call.registerParameter(2, 
    Long.class, ParameterMode.IN).bindValue(1L);
 
Output output = call.getOutputs().getCurrent();
 
if (output.isResultSet()) {
    List<Object[]> postComments = 
        ((ResultSetOutput) output).getResultList();
    assertEquals(2, postComments.size());
}

That's it!而已!

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

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