21 January 2014

Oracle object types: using constructors

As PL/SQL developer you probably have worked with object types before and maybe you also know that you can add methods (i.e. functions and procedure which operate on the object type) to your type, but did not use them.
So why should you use them or not?

First of all, it is not mandatory to use methods when working with object types in the Oracle database, but it can be handy. Especially constructors can make working with object types in PL/SQL code even easier. A constructor is a special kind of method and is a function which returns a new instance of the object and sets up the initial values of the object type. When defining an object type (CREATE OR REPLACE TYPE {object type name} AS OBJECT), a default constructor is always implicitly defined. You use that constructor to create an new instance of the object type by providing all values. But what if you do not want to provide all values or even no values at all?

In that case you need to create a constructor explictly.
In the next example we create a new object type with a constructor with no arguments:

DROP  TYPE xxp2p.xxpo_pri_matrix_gl_codes_obj FORCE;

CREATE OR REPLACE TYPE xxp2p.xxpo_pri_matrix_gl_codes_obj AS OBJECT
                  (vndr_prilist_id NUMBER,
                   po_pri_matrix_gl_code_id NUMBER,
                   gl_code VARCHAR2 (240),
                   gl_code_desc         VARCHAR2(240),
                   attribute_category VARCHAR2 (240),
                   p_mode VARCHAR2 (1),
                   CONSTRUCTOR FUNCTION xxpo_pri_matrix_gl_codes_obj
                      RETURN SELF AS RESULT);

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

TYPE xxpo_pri_matrix_gl_codes_tobj as TABLE of xxpo_pri_matrix_gl_codes_obj;

Declaration:

lpo_pri_matrix_gl_codes_obj xxpo_pri_matrix_gl_codes_obj := new xxpo_pri_matrix_gl_codes_obj();

In case of table objects

lpo_pri_matrix_gl_codes_tobj xxpo_pri_matrix_gl_codes_tobj := new xxpo_pri_matrix_gl_codes_tobj();
lpo_pri_matrix_gl_codes_tobj.extend;
lpo_pri_matrix_gl_codes_tobj(lpo_pri_matrix_gl_codes_tobj.count) := new lpo_pri_matrix_gl_codes_obj();
Then only we can assign values.
lpo_pri_matrix_gl_codes_tobj(lpo_pri_matrix_gl_codes_tobj.count).vndr_prilist_id:=1;


No comments: