其他论坛上的This answer 可能会对您有所帮助。
查看消息底部的示例,了解如何从 Java 方法(也可能是 Java 存储过程)返回的集合中进行选择。
这是一个关于如何使用 Java 存储过程的示例
1) 创建DB对象来定义返回行的类型:
create type try_obj as object (
field_a number,
field_b varchar2(10)
)
/
create type try_obj_tab as table of try_obj
/
2) 使用返回 Collection 的静态方法 (GetSampleResult) 在 DB 上创建 Java 类
create or replace and compile java source named QueryReturn as
import java.sql.*;
import java.util.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
import oracle.sql.*;
public class QueryReturn implements ORADataFactory,ORAData{
private NUMBER field1;
private CHAR field2;
public QueryReturn(OracleConnection conn,int n,String c) throws SQLException {
field1 = new NUMBER(n);
field2 = new CHAR(c,oracle.sql.CharacterSet.make(conn.getStructAttrCsId()));
}
public QueryReturn(NUMBER n, CHAR c) {
field1 = n;
field2 = c;
}
public QueryReturn(Object[] attributes) {
this(
(NUMBER) attributes[0],
(CHAR) attributes[1]
);
}
public QueryReturn(Datum d) throws SQLException {
this(((STRUCT) d).getOracleAttributes());
}
public ORAData create(Datum d, int sqlType) throws SQLException {
if (d == null)
return null;
else {
return new QueryReturn(d);
}
}
public STRUCT toSTRUCT(Connection conn) throws SQLException {
StructDescriptor sd =
StructDescriptor.createDescriptor("TRY_OBJ", conn);
Object [] attributes = { field1,field2 };
return new STRUCT(sd, conn, attributes);
}
public Datum toDatum(Connection conn) throws SQLException {
return toSTRUCT(conn);
}
public static ARRAY GetSampleResult() throws SQLException, ClassNotFoundException {
// initialize the connection
OracleConnection conn = null;
conn = (OracleConnection) (new oracle.jdbc.OracleDriver()).defaultConnection();
// create the return java array
// There will be two Rows
// 1 abc
// 2 dce
QueryReturn javaArray[] = {
new QueryReturn(conn,1,"abc"),
new QueryReturn(conn,2,"dce")
};
// Map the java class to the Oracle type
Map map = conn.getTypeMap();
map.put("TRY_OBJ", Class.forName("QueryReturn"));
ArrayDescriptor jTryObjArrayDesc = ArrayDescriptor.createDescriptor (
"TRY_OBJ_TAB",
conn
);
// create an Oracle collection on client side to use as parameter
ARRAY oracleCollection = new ARRAY(jTryObjArrayDesc,conn,javaArray);
return oracleCollection;
}
}
3) 创建 Wrap 以在函数中使用 Java 存储过程
create or replace function GetSampleResult
return try_obj_tab
AS LANGUAGE JAVA
NAME 'QueryReturn.GetSampleResult() return oracle.sql.ARRAY';
4) 显示结果
SQL> select *
2 from table(GetSampleResult())
3 /
FIELD_A FIELD_B
---------- ----------
1 abc
2 dce
SQL>