How to properly call PostgreSQL functions (stored procedures) within Spring/Hibernate/JPA?

前端 未结 6 1332
孤城傲影
孤城傲影 2021-01-12 04:11

I\'m using Spring MVC 4, Hibernate and PostgreSQL 9.3 and have defined function (stored procedure) inside Postgres like this:

CREATE OR REPLACE FUNCTION spa.         


        
6条回答
  •  南笙
    南笙 (楼主)
    2021-01-12 04:37

    I think it's the RETURN VOID that's causing the issue. So, changed the FUNCTION definition like this:

    CREATE OR REPLACE FUNCTION spa.create_tenant(t_name character varying)
      RETURNS bigint AS
      $BODY$
        BEGIN
          EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I AUTHORIZATION postgres', t_name);
          RETURN 1;
        END
      $BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION spa.create_tenant(character varying)
    OWNER TO postgres;
    

    After you changed your function to return some dummy value, change the stored procedure query to this:

    StoredProcedureQuery query = entityManager
        .createStoredProcedureQuery("spa.create_tenant")
        .registerStoredProcedureParameter(1, 
            Long.class, ParameterMode.OUT)
        .registerStoredProcedureParameter(2, 
            String.class, ParameterMode.IN)
        .setParameter(2, name);
     
    query.getResultList();
    

提交回复
热议问题