从JDBC调用Oracle面向对象的PL/SQL成员过程

Luk*_*der 8 oop oracle plsql stored-procedures jdbc

在面向对象的PL/SQL中,我可以向类型添加成员过程和函数.这里给出一个例子:

create type foo_type as object (
  foo number,

  member procedure proc(p in number),
  member function  func(p in number) return number
);

create type body foo_type as 
  member procedure proc(p in number) is begin
    foo := p*2;
  end proc;

  member function func(p in number) return number is begin
    return foo/p;
  end func;
end;
Run Code Online (Sandbox Code Playgroud)

来自:http://www.adp-gmbh.ch/ora/plsql/oo/member.html

在PL/SQL中,我可以像这样调用这些成员过程/函数:

declare
    x foo_type;
begin
    x := foo_type(5);
    x.proc(10);
    dbms_output.put_line(x.func(2));
end;
Run Code Online (Sandbox Code Playgroud)

如何使用JDBC的CallableStatement?我似乎无法在文档中轻松找到它.

注意:这是一种可能性,内联类型构造函数:

CallableStatement call = c.prepareCall(
    " { ? = call foo_type(5).func(2) } ");
Run Code Online (Sandbox Code Playgroud)

但我正在寻找的东西是这样的(java.sql.SQLData用作参数):

CallableStatement call = c.prepareCall(
    " { ? = call ?.func(2) } ");
Run Code Online (Sandbox Code Playgroud)

另外,成员函数,程序可以修改对象.如何在Java中获取修改后的对象?

Vin*_*rat 4

您可以使用变量jdbc解析和执行 PL/SQL 块out。您可以准备一个可调用的语句,例如:

declare
    x foo_type;
begin
    x := foo_type(5);
    x.proc(10);
    ? := x.func(2);
end;
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用CallableStatement.registerOutParameter,并在执行该语句后,使用适当的get函数来检索该值。

你可以在java中直接访问一个FOO_TYPE类型,但是你真的想这样做吗?请参阅下面的工作示例:

SQL> create or replace and compile java source named "TestOutParam" as
  2  import java.sql.*;
  3  import oracle.sql.*;
  4  import oracle.jdbc.driver.*;
  5  
  6  public class TestOutParam {
  7  
  8     public static int get() throws SQLException {
  9  
 10        Connection conn =
 11           new OracleDriver().defaultConnection();
 12  
 13        StructDescriptor itemDescriptor =
 14           StructDescriptor.createDescriptor("FOO_TYPE",conn);
 15  
 16        OracleCallableStatement call =
 17           (OracleCallableStatement) conn.prepareCall("declare\n"
 18              + "    x foo_type;\n"
 19              + "begin\n"
 20              + "    x := foo_type(5);\n"
 21              + "    x.proc(10);\n"
 22              + "    ? := x;\n"
 23              + "end;\n");
 24  
 25        call.registerOutParameter(1, OracleTypes.STRUCT, "FOO_TYPE");
 26  
 27        call.execute();
 28  
 29        STRUCT myObj = call.getSTRUCT(1);
 30  
 31        Datum[] myData = myObj.getOracleAttributes();
 32  
 33        return myData[0].intValue();
 34  
 35     }
 36  }
 37  /
Run Code Online (Sandbox Code Playgroud)

这是一个测试类,展示如何registerOutParameter在 SQL 对象上使用该方法,让我们调用它:

SQL> CREATE OR REPLACE
  2  FUNCTION show_TestOutParam RETURN NUMBER
  3  AS LANGUAGE JAVA
  4  NAME 'TestOutParam.get() return java.lang.int';
  5  /

Function created

SQL> select show_testoutparam from dual;

SHOW_TESTOUTPARAM
-----------------
               20
Run Code Online (Sandbox Code Playgroud)