从Java调用非默认的PLSQL对象构造函数

时间:2014-11-18 14:26:25

标签: java oracle plsql constructor

我知道如何从Java调用默认的PL / SQL构造函数。我想知道如何调用非默认构造函数。

PL / SQL代码:

CREATE OR REPLACE TYPE OBJ_DEPARTMENT IS OBJECT(
    DEPARTMENT_ID INTEGER,
    DEPARTMENT CHARACTER VARYING(100),
    CONSTRUCTOR FUNCTION OBJ_DEPARTMENT RETURN SELF AS RESULT, --1st constructor
    CONSTRUCTOR FUNCTION OBJ_DEPARTMENT(department VARCHAR2) RETURN SELF AS RESULT --2nd constructor
);
/

CREATE OR REPLACE TYPE BODY OBJ_DEPARTMENT
IS
    CONSTRUCTOR FUNCTION OBJ_DEPARTMENT RETURN SELF AS RESULT
    IS
    BEGIN
        RETURN;
    END;

    CONSTRUCTOR FUNCTION OBJ_DEPARTMENT(department VARCHAR2) RETURN SELF AS RESULT
    IS
    BEGIN
        EXECUTE IMMEDIATE '
            BEGIN
                :1:=SEQ_DEPARTMENTS.NEXTVAL();
            END;
        ' USING OUT DEPARTMENT_ID;
        SELF.DEPARTMENT:=department;
        RETURN;
    END;
END;
/

Java代码:

//calling 1st constructor
StructDescriptor structDescriptor=StructDescriptor.createDescriptor("OBJ_DEPARTMENT", oracleConnection);
STRUCT objDepartment=new STRUCT(structDescriptor, connection, new Object[]{1, "Information Technology"});

我试图在Object []中传递一个String参数来匹配第二个构造函数中的参数......

STRUCT objDepartment=new STRUCT(structDescriptor, connection, new Object[]{"Accounting"});

......但没有奏效。 如何在PL / SQL对象中调用构造函数?

1 个答案:

答案 0 :(得分:0)

在PL / SQL内部,您可以调用:

declare
  t  OBJ_DEPARTMENT;
begin
  t := OBJ_DEPARTMENT(); -- this call of your first constructor without params
end;
/

declare
  t  OBJ_DEPARTMENT;
begin
  t := new OBJ_DEPARTMENT('Some value'); -- this call of your second constructor with 1 string param
end;
/

new关键字是可选的。

顺便问一下,为什么要使用动态SQL从序列中获取nextval?在Oracle 11及更高版本中,您可以执行以下操作:

    SELF.DEPARTMENT := SEQ_DEPARTMENTS.NEXTVAL;

在早期版本中,您需要执行以下操作:

    select SEQ_DEPARTMENTS.NEXTVAL into SELF.DEPARTMENT from dual;