用StoredProcedureQuery调用Oracle函数?

时间:2014-09-03 16:27:46

标签: java jpa plsql oracle11g eclipselink

我正在尝试使用javax.persistence.StoredProcedureQuery调用Oracle PL / SQL函数,我收到错误PLS-00221: 'function_name' is not a procedure or is undefined

所以我假设不可能使用StoredProcedureQuery调用Oracle函数?

我没有看到JPA提供调用函数的接口(而不是存储过程)。那我该怎么做呢?

1 个答案:

答案 0 :(得分:2)

Oracle函数示例:

CREATE OR REPLACE FUNCTION f_get_random_number
  RETURN NUMBER
AS
BEGIN
  RETURN TRUNC(dbms_random.value(1,100));
END;

解决方案1:使用SQL查询

BigDecimal val = (BigDecimal)entityManager
                    .createNativeQuery("SELECT f_get_random_number FROM DUAL")
                    .getSingleResult();

解决方案2:使用JDBC API

Session session = entityManager.unwrap( Session.class );         
    Integer out = session.doReturningWork( 
        connection -> {
        try (CallableStatement function = connection.prepareCall("{ ? = call f_get_random_number }" )) {
            function.registerOutParameter( 1, Types.INTEGER );
            function.execute();
            return function.getInt(1);
        } 
    } );