我有一个plsql
函数,它返回记录类型challan_rec
。
create or replace package xx_bal_api as
type challan_rec is record (
challan_number varchar2(40),
challan_amount number
);
FUNCTION get_challan(foo number) return challan_rec;
end;
create or replace package body xx_bal_api as
FUNCTION get_challan(foo number) return challan_rec
is
cr challan_rec;
begin
cr.challan_number := '00002154215';
cr.challan_amount := 2265;
return cr;
end get_challan;
end;
我想从java代码调用此函数并在java中获取该记录类型。 请指导我如何做到这一点。 感谢
答案 0 :(得分:1)
首先,您只能调用从Java返回SQL对象的函数,而不是PLSQL对象。所以相应地改变你的challan_rec。整个过程应包括以下4个步骤。
在架构级别(不在包中)创建对象类型。此外,您的类型应为OBJECT类型,而不是RECORD。
CREATE OR REPLACE TYPE Some_schema.chellan_rec IS OBJECT (
challan_number varchar2(40),
challan_amount number
)
2。更改函数get_chellan以返回此对象
实现SQLData接口
public class Chellan_Rec implements SQLData{
//override readSQL, writeSQL and getSQLTypeName methods
}
从Java代码中调用PLSQL
ResultSet rs=null;
CallableStatement stmt=null;
Chellan_Rec rec = null;
try{
String sqlQuery = "{call get_chellan(?,?)}";
//map plsql type to Java type
Map m = conn.getTypeMap();
m.put("schema_name.chellan_rec", Class.forName("some_java_package.Chellan_Rec"));//this maps the Java class to the Oracle custom type
conn.setTypeMap(m);
stmt=conn.prepareCall(sqlQuery);
stmt.registerOutParameter(1, Types.STRUCT, "chellan_rec");
stmt.setObject(2, fooNum);
stmt.execute();
rec = (Chellan_Rec)stmt.getObject(1);
}catch(Exception e){
//log the exception;
}
答案 1 :(得分:0)
首先让我们开始纠正您的代码。我可以看到你发布的代码不会编译,会引发问题。正确的代码如下:
CREATE OR REPLACE PACKAGE xx_bal_api
AS
TYPE challan_rec IS RECORD
(
challan_number VARCHAR2 (40),
challan_amount NUMBER
);
TYPE rec IS TABLE OF challan_rec index by pls_integer;
FUNCTION get_challan (foo NUMBER)
RETURN rec;
END;
/
CREATE OR REPLACE PACKAGE BODY xx_bal_api
AS
FUNCTION get_challan (foo NUMBER)
RETURN rec
IS
cr rec;
BEGIN
cr (1).challan_number := '00002154215';
cr (1).challan_amount := foo;
RETURN cr;
END get_challan;
END;
执行此代码时,您可能会面临invalid datatype
等问题。这是因为RECORD
仅限于PLSQL
内使用。
select xx_bal_api.get_challan(2265) from dual;
ORA-00902:数据类型无效
执行此操作的最佳方法是创建对象的OBJECT
和TYPE
,然后在函数中创建return
:
CREATE OR REPLACE TYPE challan_rec IS OBJECT
(
challan_number VARCHAR2 (40),
challan_amount NUMBER
);
/
CREATE OR REPLACE Type rec is table of challan_rec;
/
CREATE OR REPLACE FUNCTION get_challan(foo number)
return rec
is
cr rec:=rec();
begin
cr.extend();
cr(1):= challan_rec('00002154215',foo);
return cr;
end get_challan;
end;
/
执行:
SQL> select get_challan(2265) from dual;
/